【ZZ】Python chardet 字符编码判断

使用 chardet 能够很方便的实现字符串/文件的编码检测。尤为是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,若是你须要去爬一些页面,知道网页编码很重要的,虽然HTML页面有charset标签,可是有些时候是不对的。那么chardet就能帮咱们大忙了。 python

chardet实例

>>> import urllib
>>> rawdata = urllib.urlopen('http://www.google.cn/').read()
>>> import chardet
>>> chardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
>>>

chardet能够直接用detect函数来检测所给字符的编码。函数返回值为字典,有2个元数,一个是检测的可信度,另一个就是检测到的编码。 shell

chardet 安装

下载chardet后,解压chardet压缩包,直接将chardet文件夹放在应用程序目录下,就能够使用import chardet开始使用chardet了。 ide

或者使用setup.py安装文件,将chardet拷贝到Python系统目录下,这样你全部的python程序只要用import chardet就能够了。 函数

参考 google

 

相关文章
相关标签/搜索