chardet是第三方提供的编码识别模块,具有较高的准确度。
下载
PyPI中收录有chardet,因此,借助pip下载并安装chardet即可。
pip install chardet
使用
chardet.detect(context)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
传入参数:字符串
返回值:字典,包含可信度和编码。
实例
(1)检测网页编码
import chardet
import urllib
Test = urllib.urlopen('http://www.baidu.com/').read()
print chardet.detect(Test)
输出结果:{‘confidence’: 0.99, ‘encoding’: ‘utf-8’}
(2)检测字符串编码
import chardet
import urllib
Test = "你好"
print chardet.detect(Test)
输出结果:{‘confidence’: 0.7525, ‘encoding’: ‘utf-8’}
import chardet
import urllib
Test = "Hello"
print chardet.detect(Test)
输出结果:{‘confidence’: 1.0, ‘encoding’: ‘ascii’}