Python判断字符串编码以及编码的转换

 

判断字符串编码

使用 chardet 可以很方便的实现字符串/文件的编码检测。尤其是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些页面,知道网页编码很重要

>>> import urllib
>>> html = urllib.urlopen('http://www.chinaunix.net').read()

>>> import chardet
>>> chardet.detect(html)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

函数返回值为字典,有2个元素,一个是检测的可信度,另外一个就是检测到的编码。

 

 

编码转换

先把其他编码转换为unicode再转换其他编码, 如utf-8转换为gb2312

>>> import chardet
>>> str = "我们"
>>> print(chardet.detect(str))
{'confidence': 0.7525, 'encoding': 'utf-8'}

>>> str1 = str.decode('utf-8')

>>> str2 = str1.encode('gb2312')
>>> print(chardet.detect(str2))
{'confidence': 0.8095977270813678, 'encoding': 'TIS-620'}

 

posted @ 2015-04-04 13:50  牧歌-  阅读(19052)  评论(1编辑  收藏  举报