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
- python 模块 chardet
- Python chardet模块
- python 中使用 chardet 模块
- python编码检测模块chardet
- Python的chardet模块安装
- python chardet模块查看编码
- 探测python中字符集模块chardet
- python 模块 chardet下载方法及介绍
- Mac os Python 安装 chardet模块
- python模块chardet下载及介绍
- python 模块 chardet下载方法及介绍
- python chardet模块 检测文档编码
- python 模块 chardet下载方法及介绍
- python使用模块chardet判断字符编码
- [Python模块学习]chardet模块识别字节包编码
- python chardet
- Python | 多种编码文件(中文)乱码问题解决 chardet模块
- chardet字符集检测模块
- android 状态选择器和shape的运用
- 矩阵乘法
- 【ARM-Linux开发】cmem模块/DVSDK2.0
- mysql数据库中文出现乱码
- MFC使用CEF内核,Browser进程与Renderer进程之间的通信(***)
- Python chardet模块
- Ubuntu 软件安装、查找、卸载--apt-get、apt-cache命令安全
- 【ARM-Linux开发】Linux内存管理:ARM Memory Layout以及mmu配置
- ECMAScript2015(ES6)概要
- Redis分页排序查询
- 技术博客初体验~
- 勾股定理一日一证连载173
- iOS 瀑布流总结
- Autodesk Forge 问题的支持通道