你如何在Python中解码多个和未知的字符集?

vwi*_*rek 3 python character-encoding

我做了很多文本解析,但似乎总是遇到解码问题.通常,我只是通过以下方式查找编码:

$ file -i filename.txt
filename.txt: text/x-diff; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

然后,通过我的读取行指定它(这里使用io显示).

io.open(filename.txt, 'r', encoding='utf-8')

但是,每当我遇到新的文件编码时,我得到:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x0a in position 0: truncated data'

我必须重复手动检测和设置新编码的过程.有没有更好的方法来解析具有多个和未知字符集的多个文件?我尝试过try/except块来成功处理两个编码,但是三个或更多呢?有自动检测方法吗?

Dhr*_*hak 5

您可以使用此python包:https: //pypi.python.org/pypi/chardet

它会尝试猜测编码,然后您可以继续进行输入处理.