development

파이썬 문자열은 [u'String ']으로 인쇄

big-blog 2020. 7. 3. 17:57
반응형

파이썬 문자열은 [u'String ']으로 인쇄


이것은 분명히 쉬운 일이지만 실제로 나를 괴롭 힙니다.

웹 페이지를 읽고 Beautiful Soup사용 하여 구문 분석 하는 스크립트가 있습니다. 로부터 수프 나의 최종 목표는 link.contents을 인쇄하는 것입니다 나는 모든 링크를 추출합니다.

구문 분석하는 모든 텍스트는 ASCII입니다. 나는 파이썬이 문자열을 유니 코드로 취급한다는 것을 알고 있으며, 이것이 내 스크립트에서 전혀 사용되지 않는 매우 편리하다고 확신합니다.

'String'을 포함하는 변수를 [u'String']인쇄 할 때마다 화면에 인쇄됩니다. 이것을 ascii로 되 돌리는 간단한 방법이 있습니까? 아니면 정규식을 작성하여 제거해야합니까?


[u'ABC']유니 코드 문자열의 한 요소 목록입니다. Beautiful Soup은 항상 유니 코드를 생성합니다 . 따라서 목록을 단일 유니 코드 문자열로 변환 한 다음 ASCII로 변환해야합니다.

나는 당신이 어떻게 한 원소 목록을 얻었는지에 대해 잘 모릅니다. 내용 멤버는 문자열과 태그의 목록이 될 것입니다. 당신이 정말로 항상 하나의 요소 목록을 얻을 수 있다고 가정하고 시험은 정말되는 경우에만 이을 사용 ASCII :

 soup[0].encode("ascii")

그러나 데이터가 실제로 ASCII인지 다시 확인하십시오. 이것은 매우 드 rare니다. 라틴어 또는 utf-8 일 가능성이 큽니다.

 soup[0].encode("latin-1")


 soup[0].encode("utf-8")

또는 Beautiful Soup에게 원래 인코딩이 무엇인지 물어 보고이 인코딩으로 다시 가져 오십시오.

 soup[0].encode(soup.originalEncoding)

유니 코드 문자열이 하나 포함 된 목록이있을 수 있습니다. repr이의입니다 [u'String'].

다음을 변형하여이를 바이트 문자열 목록으로 변환 할 수 있습니다.

# Functional style.
print map(lambda x: x.encode('ascii'), my_list)

# List comprehension.
print [x.encode('ascii') for x in my_list]

# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode('ascii') for x in my_list)

# What do I care about the brackets anyway?
print ', '.join(repr(x.encode('ascii')) for x in my_list)

# That's actually not a good way of doing it.
print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list)

import json, ast
r = {u'name': u'A', u'primary_key': 1}
ast.literal_eval(json.dumps(r)) 

인쇄합니다

{'name': 'A', 'primary_key': 1}

단일 요소 목록에 액세스 / 인쇄하는 경우 (예 : 순차적 또는 필터링 된) :

my_list = [u'String'] # sample element
my_list = [str(my_list[0])]

출력을 str () 함수에 전달하면 유니 코드 출력 변환이 제거됩니다. 또한 출력을 인쇄하여 u ''태그를 제거합니다.


사용 dir또는 type'문자열'에 그것이 무엇인지 찾을 수 있습니다. 문자열처럼 인쇄되는 BeautifulSoup의 태그 객체 중 하나라고 생각하지만 실제로는 그렇지 않습니다. 그렇지 않으면 목록 안에 있으며 각 문자열을 개별적으로 변환해야합니다.

어쨌든 유니 코드 사용에 반대하는 이유는 무엇입니까? 특별한 이유가 있습니까?


당신은 정말로 의미 u'String'합니까?

어쨌든 str(string)유니 코드 문자열이 아닌 문자열을 얻는 것이 어떻습니까? (모든 문자열이 유니 코드 인 Python 3에서는 달라야합니다.)


[u'String'] 파이썬 2에서 유니 코드 문자열을 포함하는 목록의 텍스트 표현입니다.

당신이 실행하는 경우 print(some_list)는 동일합니다 다음
print'[%s]' % ', '.join(map(repr, some_list))즉, 유형의 파이썬 객체의 텍스트 표현을 생성 list, repr()기능은 각 항목에 대해 호출됩니다.

파이썬 객체와 텍스트 표현을 혼동하지 마십시오 - repr('a') != 'a'텍스트 표현 다르다 심지어 텍스트 표현을 : repr(repr('a')) != repr('a').

repr(obj)인쇄 가능한 객체 표현이 포함 된 문자열을 반환합니다. REPL에서 디버깅에 유용 할 수있는 객체를 명확하게 표현하는 것이 목적입니다. 종종 eval(repr(obj)) == obj.

To avoid calling repr(), you could print list items directly (if they are all Unicode strings) e.g.: print ",".join(some_list)—it prints a comma separated list of the strings: String

Do not encode a Unicode string to bytes using a hardcoded character encoding, print Unicode directly instead. Otherwise, the code may fail because the encoding can't represent all the characters e.g., if you try to use 'ascii' encoding with non-ascii characters. Or the code silently produces mojibake (corrupted data is passed further in a pipeline) if the environment uses an encoding that is incompatible with the hardcoded encoding.


encode("latin-1") helped me in my case:

facultyname[0].encode("latin-1")

Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText

        avail = []
        avail = driver.find_elements_by_class_name("label");
        for i in avail:
                if  i.text == "MyText":

Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?

참고URL : https://stackoverflow.com/questions/599625/python-string-prints-as-ustring

반응형