0

这是代码(chardet(https://pypi.python.org/pypi/chardet)-通用编码检测器)

import chardet

try: 
    for f in os.listdir(path):
        print f, chardet.detect(f)['encoding'], f.decode(chardet.detect(f)['encoding'])
except Exception, e: 
    print str(e)

输出

qiwi2.sql ascii qiwi2.sql
www ascii www
’ҐЄбв®ўл© ¤®Єг¬Ґ­в.txt windows-1252 
'ascii' codec can't encode characters in position 0-8: ordinal not in range(128)
4

1 回答 1

1

问题出在print. 它不知道控制台输出使用什么编码,所以它假设ASCII, 并encode自动执行并失败。如果你encode自己做它应该工作。

print f, chardet.detect(f)['encoding'], f.decode(chardet.detect(f)['encoding']).encode('utf-8')
于 2013-11-03T04:50:37.210 回答