2010-05-18 6 views
9

저는 며칠 동안 파이썬을 알았습니다. 유니 코드는 파이썬에서 문제가되는 것 같습니다.이스케이프 된 문자열을 파이썬에서 유니 코드로 표시

은 내가 파일을 읽고 문자열을 인쇄 할 수있는 텍스트 문자열이

'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

같은 텍스트 파일을 저장을 가지고 있지만 그것은 잘못 표시됩니다.

+1

"문자열을 출력하십시오"라는 말은 콘솔을 의미합니까? 그렇다면 아마 여러분의 콘솔이 문제 일 것입니다 - 유니 코드 문자를 지원하는지 확실합니까? –

답변

0

이것은 Terminal.App 제대로 맥에서 작동이

>>> s=u"\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1" 
>>> print s 
=> Đèn đỏ nút giao thông Ngã tư Láng Hạ 
8
>>> x=r'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 
>>> u=unicode(x, 'unicode-escape') 
>>> print u 
Đèn đỏ nút giao thông Ngã tư Láng Hạ 

시도 사전에

"Đèn đỏ nút giao thông Ngã tư Láng Hạ" 

감사 : 어떻게 다음과 같이 올바르게 화면에 그것을 밖으로 인쇄 할 수 있습니다 sys.stdout.encodingutf-8으로 설정하십시오. 플랫폼이 올바르게 (또는 모두) 그 속성을 설정하지 않는 경우,

print u.decode('utf8') 

또는 어떤 다른/콘솔이 사용하는 터미널을 인코딩과 마지막 줄을 교체해야합니다.

첫 번째 줄에서는 "이스케이프 시퀀스"가 확장되지 않도록 원시 문자열 리터럴을 할당합니다. 즉, 바이트 문자 x이 (텍스트 또는 이진) 파일에서 읽혀지면 발생하는 상황을 모방 한 것입니다. 그 문자 적 ​​내용.

1

코드로 간단한 예제를 보여주고 명시 적으로 시도한 것을 출력하는 데 도움이됩니다. 추측 컨대 당신의 콘솔은 베트남어를 지원하지 않습니다. 다음은 몇 가지 옵션입니다.

# A byte string with Unicode escapes as text. 
>>> x='\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

# Convert to Unicode string. 
>>> x=x.decode('unicode-escape') 
>>> x 
u'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1' 

# Try to print to my console: 
>>> print x 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\dev\python\lib\encodings\cp437.py", line 12, in encode 
    return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0110' in position 0: 
    character maps to <undefined> 

# My console's encoding is cp437. 
# Instead of the default strict error handling that throws exceptions, try: 
>>> print x.encode('cp437','replace') 
?èn ?? nút giao thông Ng? t? Láng H?  

# Six characters weren't supported. 
# Here's a way to write the text to a temp file and display it with another 
# program that supports the UTF-8 encoding: 
>>> import tempfile 
>>> f,name=tempfile.mkstemp() 
>>> import os 
>>> os.write(f,x.encode('utf8')) 
48 
>>> os.close(f) 
>>> os.system('notepad.exe '+name) 

희망이 있습니다.

관련 문제