在Python中将转义字符串显示为Unicode

时间:2010-05-18 08:37:04

标签: python unicode escaping

我刚认识Python几天了。 Unicode似乎是Python的一个问题。

我有一个文本文件存储像这样的文本字符串

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

我可以读取文件并打印出字符串,但显示不正确。 如何将其打印出来以正确显示如下:

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

提前致谢

3 个答案:

答案 0 :(得分: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ạ

这适用于Mac,其中Terminal.App正确地将sys.stdout.encoding设置为utf-8。如果您的平台没有正确设置该属性(或根本没有),则需要用

替换最后一行
print u.decode('utf8')

或您的终端/控制台正在使用的任何其他编码。

请注意,在第一行中我分配了一个原始字符串文字,以便不会展开“转义序列” - 这只是模仿了从(文本或二进制文件)读取bytestring x时会发生什么)具有该文字内容的文件。

答案 1 :(得分: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)

希望对你有所帮助。

答案 2 :(得分:0)

试试这个

>>> 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ạ