Python中如何将转义字符串显示为Unicode?

9
我刚学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ạ"

提前感谢您。

1
“打印字符串”是指输出到控制台吗?如果是,那可能是您的控制台有问题了 - 你确定它支持Unicode字符吗? - Dominic Rodger
3个回答

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.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)

希望这能对你有所帮助。


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ạ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接