Python chardet模块

来源:互联网 发布:115会员淘宝如何搜索 编辑:程序博客网 时间:2024/05/14 04:30

1. chardet是什么

  chardet是python的一个第三方编码检测模块,可以检测文件,XML等字符编码的类型。通过pip install chardet安装使用。

2.chardet怎么用

  • 1.通过命令行直接调用(chardet提供了一个命令行工具,可以直接使用),形如chardet somefile someotherfile的样式。
    这里写图片描述上面先创建了一个文件并向里面写入一些内容,然后通过chardet命令行调用检测文件编码方式。检测结果为utf8,可信度为75%。
  • 2.通过引入模块,调用方法使用。
from chardet import detectcs = '中国'js = 'ジャパン'ks = '한국인'cs_ef = detect(cs.decode('utf8').encode('gbk'))js_ef = detect(js.decode('utf8').encode('euc_jp'))ks_ef = detect(js.decode('utf8').encode('euc_kr'))

使用也很简单,直接使用detect方法即可。之所以先编号码,再去检测,是想看一看检测结果怎么样。下面是结果。

这里写图片描述

gbk兼容gb2312,没问题。euc_jp是日文的一种编码方式,韩文的euc_kr倒是被检测为了ibm866,维基百科上866的编码如下所示,貌似有点对不上。

这里写图片描述

下面再写几个例子试试看效果。检测目标为中日韩美德五个网站编码方式。

from chardet import detectfrom urllib import urlopenurls = [    'http://www.yau.edu.cn/',    'http://www.nhk.or.jp/',    'http://www.kbs.co.kr/',    'http://edition.cnn.com/',    'https://de.yahoo.com/']for url in urls:    resp = urlopen(url)    print (url, detect(resp.read()))

下面是测试结果。

这里写图片描述

大都是utf8编码的(也理应如此)。那个韩文网站检测为euc_kr编码方式。上面应该再加个验证的,就是顺便把网站的编码从网页上找出来,然后和chardet检测出的结果做个对比。下面加上。

import refrom chardet import detectfrom urllib import urlopenurls = [    'http://www.yau.edu.cn/',    'http://www.nhk.or.jp/',    'http://www.kbs.co.kr/',    'http://edition.cnn.com/',    'https://de.yahoo.com/']p = re.compile(r'<meta[^<]+charset[^>]+>')for url in urls:    resp = urlopen(url).read()    res = re.search(p, resp)    print (url, detect(resp), res.group())

下面看一看结果如何。

这里写图片描述

通过结果可知这些网站编码检测的结果与实际结果是一致的。

3.注意事项

在chardet源码里的detect函数是这样定义的:

__version__ = "2.3.0"from sys import version_infodef detect(aBuf):    if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or            (version_info >= (3, 0) and not isinstance(aBuf, bytes))):        raise ValueError('Expected a bytes object, not a unicode object')    from . import universaldetector    u = universaldetector.UniversalDetector()    u.reset()    u.feed(aBuf)    u.close()    return u.result

这意味着在py3中不能使用str字符串,需要使用bytes字符串。

这里写图片描述

0 0
原创粉丝点击