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

转自:http://www.cnblogs.com/zhanhg/p/4392089.html

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

判断字符串编码:

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

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import urllib, chardet

if __name__ == '__main__':
    html = urllib.urlopen('http://www.baidu.com').read()
    print chardet.detect(html)
  结果:
{'confidence': 0.99, 'encoding': 'utf-8'}

  

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

编码转换:

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

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import chardet

if __name__ == '__main__':
    str = raw_input("请输入地址:")
    print chardet.detect(str)

    str1 = str.decode('utf-8')
    str2 = str1.encode('gb2312')
    print chardet.detect(str2)
  结果:
请输入地址:你好
{'confidence': 0.7525, 'encoding': 'utf-8'}
{'confidence': 0.3598212120361634, 'encoding': 'TIS-620'}

 

结束语:

  示例中使用到了chardet模块,所以需要先安装该模块才能按示例代码按步骤操作得到相应的结果。

原文地址:https://www.cnblogs.com/pizitai/p/6476296.html