Python: 使用 unicode 字符

Python: working with unicode characters

我正在尝试学习如何在 python 中使用 Unicode。

假设我有一个包含 Unicode 字符的文件 testáéíóúabcdefgçë 我想制作一个 python 脚本来打印出文件中的所有唯一字符。这是我的:

#!/usr/bin/python

import sys

def main():
    if len(sys.argv) < 2:
        print("Argument required.")
        exit()
    else:
        filename = sys.argv[1]
        with open(filename, "r") as fp:
            string = fp.read().replace('\n', '')
        chars = set()
        for char in string:
            chars.add(char)
        for char in chars:
            sys.stdout.write(char)
        print("")

if __name__ == "__main__":
    main()

这不能正确打印 Unicode 字符:

$ ./unicode.py test
▒a▒bedgf▒▒▒▒c▒▒

执行此操作的正确方法是什么才能正确打印字符?

这取决于您使用的 Python 版本:

1. 对于 python 2,没有对 Unicode 字符的原生支持,所以有必要保留显式,使用 header如:

# -*-coding:utf-8-*-

2. For python 3 支持是原生的,如其所说here.

所以 UTF-8 编码已经有了本地支持。

您的数据已编码,很可能是 utf-8。 Utf-8使用多字节编码非ASCII字符,如áéíóú。迭代编码为 utf-8 的字符串会产生构成字符串的单个 bytes,而不是您期望的 characters

>>> s = 'áéíóúabcdefgçë'
# There are 14 characters in s, but it contains 21 bytes
>>> len(s)
21
>>> s
'\xc3\xa1\xc3\xa9\xc3\xad\xc3\xb3\xc3\xbaabcdefg\xc3\xa7\xc3\xab'

# The first "character" (actually, byte) is unprintable.
>>> print s[0]
�
# So is the second.
>>> print s[1]
�
# But together they make up a character.
>>> print s[0:2]
á

所以打印单个字节没有按预期工作。

>>> for c in s:print c,
... 
� � � � � � � � � � a b c d e f g � � � �

但是将字符串解码为 un​​icode,然后打印。

>>> for c in s.decode('utf-8'):print c,
... 
á é í ó ú a b c d e f g ç ë

为了使您的代码按预期工作,您需要解码从文件中读取的字符串。更改

string = fp.read().replace('\n', '')

string = fp.read().replace('\n', '').decode('utf-8')