我正在使用file.readline()在Python中读取包含罗马尼亚语单词的文件。 由于编码,我遇到了许多字符的问题。
示例:
>>> a = "aberație" #type 'str'
>>> a -> 'abera\xc8\x9bie'
>>> print sys.stdin.encoding
UTF-8
我已尝试使用utf-8,cp500等编码(),但它不起作用。
我找不到哪个正确的字符编码我必须使用?
提前感谢。
编辑:目的是将文件中的单词存储在一个字典中,并在打印时获取aberaţie而不是'abera \ xc8 \ x9bie'
答案 0 :(得分:15)
你想做什么?
这是一组字节:
BYTES = 'abera\xc8\x9bie'
这是一组字节,表示字符串“aberaţie”的utf-8
编码。您解码字节以获取您的unicode字符串:
>>> BYTES
'abera\xc8\x9bie'
>>> print BYTES
aberație
>>> abberation = BYTES.decode('utf-8')
>>> abberation
u'abera\u021bie'
>>> print abberation
aberație
如果要将unicode字符串存储到文件中,则必须将编码为您选择的特定字节格式:
>>> abberation.encode('utf-8')
'abera\xc8\x9bie'
>>> abberation.encode('utf-16')
'\xff\xfea\x00b\x00e\x00r\x00a\x00\x1b\x02i\x00e\x00'