17.python字符编码检测——chardet

                当面对一串不知道编码信息的字节流的时候,尝试着确定一种编码方式以使我们能够读懂其中的文本内容。类似于破解密码。
                Firefox包含有一个自动检测字符编码的库,导入到了python2,并且取绰号为chardet模块
                chardet运用了一种算法来检测字符的类型

import chardet
utf8_str = '我爱python'
gbk_str = utf8_str.decode('UTF-8').encode('GBK')

print utf8_str,chardet.detect(utf8_str)
print gbk_str,chardet.detect(gbk_str)


输出:

我爱python {'confidence': 0.7525, 'encoding': 'utf-8'}
我爱python {'confidence': 0.99, 'encoding': 'GB2312'}


 

原文地址:https://www.cnblogs.com/chenjianhong/p/4145126.html