在Python中以Unicode顯示逃逸字符串

2024-06-14 14:08:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚认识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ạ"

提前谢谢


Tags: 字符串文本unicodeng文本文件thxe3u0111
3条回答

试试这个

>>> 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ạ
>>> 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会发生什么。

它有助于用代码展示一个简单的示例,并输出您显式尝试过的内容。估计你的游戏机不支持越南语。以下是一些选项:

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

希望这对你有帮助。

相关问题 更多 >