python 第三方库 chardet

时间:2023-11-22 14:31:38

chardet是一个非常优秀的编码识别模块。
chardet 是python的第三方库,需要下载和安装,放在python安装根目录\Lib\site-packages下面

import chardet
import urllib #可根据需要,选择不同的数据
TestData = urllib.urlopen('http://www.baidu.com/').read()
print chardet.detect(TestData) 运行结果:
{'confidence': 0.99, 'encoding': 'GB2312'}

运行结果表示有99%的概率认为这段代码是GB2312编码方式。

更高级应用:

import urllib
from chardet.universaldetector import UniversalDetector
usock = urllib.urlopen('http://www.baidu.com/')
#创建一个检测对象
detector = UniversalDetector()
for line in usock.readlines():
#分块进行测试,直到达到阈值
detector.feed(line)
if detector.done: break
#关闭检测对象
detector.close()
usock.close()
#输出检测结果
print detector.result 运行结果:
{'confidence': 0.99, 'encoding': 'GB2312'}

应用背景,如果要对一个大文件进行编码识别,使用这种高级的方法,可以只读一部,去判别编码方式从而提高检测速度。

参考资料:http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece7631046893b4c4380146d96864968d4e414c42246071c35bff37d651304d2d82f2747f41802bded602571507be9dad58249d7be942d2d9c6269304a8903599543f2975125b071ca09a9f94ea1&p=9e3f865bc5904ead08e2947d0f5da5&newp=9234c64ad48309f30cbd9b7e0e148b231610db2151d7d3146b82c825d7331b001c3bbfb423221b01d7c6776302aa4856e8f732743c0821a3dda5c91d9fb4c57479c86f6824&user=baidu&fm=sc&query=python+chardet&qid=a082077700050a7d&p1=1