python字符编码检测——chardet

来源:互联网 发布:淘宝靠谱的足球鞋店铺 编辑:程序博客网 时间:2024/05/21 19:45

分类: 我的python新生 2012-04-01 15:36 21人阅读 评论(0) 收藏 举报
                当面对一串不知道编码信息的字节流的时候,尝试着确定一种编码方式以使我们能够读懂其中的文本内容。类似于破解密码。
                Firefox包含有一个自动检测字符编码的库,导入到了python2,并且取绰号为chardet模块
                chardet运用了一种算法来检测字符的类型
[python] view plaincopy
import chardet  
utf8_str = '我爱python'  
gbk_str = utf8_str.decode('UTF-8').encode('GBK')  
  
print utf8_str,chardet.detect(utf8_str)  
print gbk_str,chardet.detect(gbk_str)  


输出:
[python] view plaincopy
我爱python {'confidence': 0.7525, 'encoding': 'utf-8'}  
我爱python {'confidence': 0.99, 'encoding': 'GB2312'}  
原创粉丝点击