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

yipeiwu_com6年前Python基础

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'}

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

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

相关文章

python开发环境PyScripter中文乱码问题解决方案

PyScripter看起来还是挺不错的一个python ide 环境: PyScripter 2.6.0.0 python3.4 问题: PyScripter有个小坑,打开文件后中文都成...

linux下安装easy_install的方法

如果想使用easy_install工具,可能需要先安装setuptools,不过更酷的方法是使用ez_setup.py脚本:复制代码 代码如下:wget -q http://peak.t...

python-numpy-指数分布实例详解

如下所示: # Seed random number generator np.random.seed(42) # Compute mean no-hitter time: ta...

pyqt5 禁止窗口最大化和禁止窗口拉伸的方法

如下所示: 在def __init__(self):函数里添加 self.setFixedSize(self.width(), self.height()) 以上这篇pyqt5 禁止窗口...

Python命名空间详解

通俗的来说,Python中所谓的命名空间可以理解为一个容器。在这个容器中可以装许多标识符。不同容器中的同名的标识符是不会相互冲突的。理解python的命名空间需要掌握三条规则: 第一,赋...