首页 > 解决方案 > 将 unicode 列表转换为可读格式

问题描述

我正在使用多语种来标记缅甸语中的文本。这就是我正在做的事情。

    from polyglot.text import Text

    blob = u"""
ထိုင္းေရာက္ျမန္မာလုပ္သားမ်ားကို လုံၿခဳံေရး အေၾကာင္းျပၿပီး ထိုင္းရဲဆက္လက္ဖမ္းဆီး၊ ဧည့္စာရင္းအေၾကာင္းျပ၍ ဒဏ္ေငြ႐ိုက္
"""
    text = Text(blob)

当我做 :

print(text.words)

它以以下格式输出:

[u'\u1011\u102d\u102f', u'\u1004\u1039\u1038\u1031', u'\u101b\u102c', u'\u1000\u1039\u103b', u'\u1019', u'\u1014\u1039', u'\u1019\u102c', u'\u101c\u102f', u'\u1015\u1039', u'\u101e\u102c\u1038', u'\u1019\u103a\u102c\u1038', u'\u1000\u102d\u102f', u'\u101c\u102f\u1036', u'\u107f', u'\u1001\u1033\u1036\u1031', u'\u101b\u1038', u'\u1021\u1031\u107e', u'\u1000\u102c', u'\u1004\u1039\u1038\u103b', u'\u1015\u107f', u'\u1015\u102e\u1038', u'\u1011\u102d\u102f', u'\u1004\u1039\u1038', u'\u101b\u1032', u'\u1006', u'\u1000\u1039', u'\u101c', u'\u1000\u1039', u'\u1016', u'\u1019\u1039\u1038', u'\u1006\u102e\u1038', u'\u104a', u'\u1027', u'\u100a\u1037\u1039', u'\u1005\u102c', u'\u101b', u'\u1004\u1039\u1038', u'\u1021\u1031\u107e', u'\u1000\u102c', u'\u1004\u1039\u1038\u103b', u'\u1015', u'\u104d', u'\u1012', u'\u100f\u1039\u1031', u'\u1004\u103c\u1090\u102d\u102f', u'\u1000\u1039']

这是什么输出?我不确定为什么输出是这样的。我怎样才能将它转换回我可以从中理解的格式?

我还尝试了以下方法:

text.words[1].decode('unicode-escape')

但它抛出一个错误说:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

标签: pythonunicodetokenizepython-unicode

解决方案


这就是 Python 2 打印列表的方式。它是调试输出(参见repr()),它明确指示列表的内容。 u''表示Unicode字符串,\uxxxx表示U+xxxx的Unicode码位。输出全部为 ASCII,因此它适用于任何终端。如果您直接打印列表中的字符串,如果您的终端支持正在打印的字符,它们将正确显示。例子:

words = [u'\u1011\u102d\u102f', u'\u1004\u1039\u1038\u1031', u'\u101b\u102c']
print words
for word in words:
    print word

输出:

[u'\u1011\u102d\u102f', u'\u1004\u1039\u1038\u1031', u'\u101b\u102c']
ထို
င္းေ
ရာ

再次强调,您的终端必须配置支持 Unicode 代码点(理想情况下为 UTF-8)的编码,并使用支持字符的字体。否则,您可以将文本打印到 UTF-8 编码的文件中,然后在支持 UTF-8 且具有支持字符的字体的编辑器中查看该文件:

import io
with io.open('example.txt','w',encoding='utf8') as f:
    for word in words:
        f.write(word + u'\n')

切换到 Python 3,事情变得更加简单。如果终端支持,它默认显示字符,但您仍然可以获得调试输出:

words = [u'\u1011\u102d\u102f', u'\u1004\u1039\u1038\u1031', u'\u101b\u102c']
print(words)
print(ascii(words))

输出:

['ထို', 'င္းေ', 'ရာ']
['\u1011\u102d\u102f', '\u1004\u1039\u1038\u1031', '\u101b\u102c']

推荐阅读