在Python中以Unicode显示转义字符串

9 投票
3 回答
8790 浏览
提问于 2025-04-15 22:50

我刚学了几天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

试试这个

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

希望这些对你有帮助。

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

或者你终端/控制台正在使用的其他编码。

注意,在第一行我使用了一个原始字符串字面量,这样“转义序列”就不会被展开——这只是模拟了如果字节字符串x是从一个(文本或二进制)文件中读取的那种内容。

撰写回答