我想读取一个文件,其中包含德语字符而不仅限于英文字符。我发现可以这样做:
>>> import codecs
>>> file = codecs.open('file.txt','r', encoding='UTF-8')
>>> lines= file.readlines()
当我尝试在Python IDLE中运行作业时,它可以正常工作,但当我尝试从其他地方运行它时,它就无法给出正确的结果。有什么想法吗?
您需要知道文本使用的字符编码。如果事先不知道,可以尝试使用chardet模块进行猜测。首先安装它:
$ pip install chardet
例如,在二进制模式下读取文件:
>>> import chardet
>>> chardet.detect(open("file.txt", "rb").read())
{'confidence': 0.9690625, 'encoding': 'utf-8'}
那么:
>>> import codecs
>>> import unicodedata
>>> lines = codecs.open('file.txt', 'r', encoding='utf-8').readlines()
import codecs
。 - duhaime我相信这个文件被正确读取了,但在输出时使用了错误的编码。这是基于您在IDLE中获得正确结果的事实。
我建议尝试使用print(line.encode('utf-8'))
,但我担心 Python 3 是否能够正确打印一个字节对象。
open('file.txt', 'rb').readlines()
以二进制模式读取文件,然后对于你知道包含德语字符的行使用print(repr(line))
,并且输出你期望的结果。这应该有助于确定编码方式。 - Andrew Clarkreadlines()
可能在二进制模式下不起作用,请尝试print(repr(open('file.txt', 'rb').read()))
,然后发布全部或部分输出。 - Andrew Clark