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

来源:互联网 发布:mac 设置homekit 编辑:程序博客网 时间:2024/05/16 14:42

判断字符串编码

使用 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'}
复制代码
0 0
原创粉丝点击