当前位置:Gxlcms > Python > Python使用chardet判断字符编码

Python使用chardet判断字符编码

时间:2021-07-01 10:21:17 帮助过:64人阅读

本文实例讲述了Python使用chardet判断字符编码的方法。分享给大家供大家参考。具体分析如下:

Python中chardet 用来实现字符串/文件编码检测模板

1、chardet下载与安装

下载地址:http://pypi.python.org/pypi/chardet

下载chardet后,解压chardet压缩包,直接将chardet文件夹放在应用程序目录下,就可以使用import chardet开始使用chardet了,也可以将chardet拷贝到Python系统目录下,这样你所有的python程序只要用import chardet就可以了。

  1. python setup.py install

2、实例

使用中,chardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式

(1)网页编码判断:

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

(2)文件编码判断

  1. import chardet
  2. tt=open('c:\\111.txt','rb')
  3. ff=tt.readline()
  4. #这里试着换成read(5)也可以,但是换成readlines()后报错
  5. enc=chardet.detect(ff)
  6. print enc['encoding']
  7. tt.close()

希望本文所述对大家的Python程序设计有所帮助。

人气教程排行