python2.7:文件编码检测chardet 详解

来源:互联网 发布:nba总决赛欧文数据统计 编辑:程序博客网 时间:2024/05/21 19:28
# coding=utf-8import os,chardetprint os.getcwd() # 打印当前工作目录os.chdir("C:\Users\Administrator\Desktop\Pyhton2.7Tests") # 修改当前工作目录f = open("chardet_test.txt", "r")result = chardet.detect(f.read()) # chardet.detect()方法返回一个字典,confidence是精确度,encoding是编码格式。print result f.close()import urllib2 # 测试网页编码d = urllib2.urlopen("http://www.baidu.com") print chardet.detect(d.read())d.close()   # GB2312是中国规定的汉字编码,也可以说是简体中文的字符集编码;GBK 是 GB2312的扩展 ,除了兼容GB2312外,它还能显示繁体中文,还有日文的假名        # chardet.detect检测到的编码是GB2312,但是实际上的应该是 <meta http-equiv="Content-Type" content="text/html; charset=gbk" />        # 网页是GBK,所以此时的精确度是99%。# 输出# D:\Program Files (x86)\Notepad++# {'confidence': 1.0, 'encoding': 'ascii'}# {'confidence': 0.99, 'encoding': 'utf-8'}# 请按任意键继续. . .

0 0
原创粉丝点击