python字符串编码识别模块chardet简单应用

WBOY
Release: 2016-06-10 15:10:33
Original
1064 people have browsed it

python的字符串编码识别模块(第三方库):

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

 
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'}
Copy after login

应用背景,如果要对一个大文件进行编码识别,使用这种高级的方法,可以只读一部,去判别编码方式从而提高检测速度。如果希望使用一个检测对象检测多个数据,在每次检测完,一定要运行一下detector.reset()。清除之前的数据。

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!