python 文本编码识别 file magic有时候不准

试了用magic模块,但是有的文件里面是中文的(notepad++打开显示为unix ansi ,notepad++能正常打开显示),却被magic判断为"ISO 8859-1"。而用python chardet模块识别后,该文本内容编码为“GB2312”,且读取后用该编码方式能正确显示。

cnt = self.getFileContent(filepathstr)
codecname = chardet.detect(cnt).get('encoding')
if codecname != "":
    codec = QTextCodec.codecForName( codecname)
    print "codecname %s\n"%codecname
    decoder = codec.makeDecoder()
    encodedString = decoder.toUnicode(cnt)
else:
    encodedString = cnt

self.mytextWidget.setText(QString(encodedString))

本人文章除注明转载外,均为本人原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创开源社区
转载请注明:文章转载自:开源中国社区 [http://www.oschina.net]
本文标题:python 文本编码识别 file magic有时候不准
本文地址:http://my.oschina.net/kjpioo/blog/147455

你可能感兴趣的:(python,编码,qt,encoding,chardet)