您的位置:首页 > 编程语言 > Python开发

python chardet简单应用

2015-06-14 16:24 821 查看
python的字符串编码识别模块(第三方库):

官方地址:http://pypi.python.org/pypi/chardet

importchardet

importurllib


#可根据需要,选择不同的数据

TestData=urllib.urlopen('http://www.baidu.com/').read()

printchardet.detect(TestData)


#运行结果:

#{'confidence':0.99,'encoding':'GB2312'}


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

importurllib

fromchardet.universaldetectorimportUniversalDetector

usock=urllib.urlopen('http://www.baidu.com/')

#创建一个检测对象

detector=UniversalDetector()

forlineinusock.readlines():

#分块进行测试,直到达到阈值

detector.feed(line)

ifdetector.done:break

#关闭检测对象

detector.close()

usock.close()

#输出检测结果

printdetector.result


#运行结果:

#{'confidence':0.99,'encoding':'GB2312'}


应用背景,如果要对一个大文件进行编码识别,使用这种高级的方法,可以只读一部,去判别编码方式从而提高检测速度。如果希望使用一个检测对象检测多个数据,在每次检测完,一定要运行一下detector.reset()。清除之前的数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: