python笔记:常用第三方模块—chardet

目录

一、安装chardet

二、使用chardet

2.1对bytes检测编码

2.2对GBK编码的中文检测编码

2.3对UTF-8编码检测编码

2.4对日文检测编码


     字符串编码一直是令人非常头疼的问题,尤其是我们在处理一些不规范的第三方网页的时候。虽然Python提供了Unicode表示的strbytes两种数据类型,并且可以通过encode()decode()方法转换,但是,在不知道编码的情况下,对bytesdecode()不好做。chardet这个第三方库正好就派上了用场。用它来检测编码,简单易用。

一、安装chardet

如果安装了Anaconda,chardet就已经可用了。否则,需要在命令行下通过pip安装:

$ pip install chardet

如果遇到Permission denied安装失败,请加上sudo重试。

二、使用chardet

2.1对bytes检测编码

用chardet检测编码,只需要一行代码:

扫描二维码关注公众号,回复: 2306986 查看本文章
>>> chardet.detect(b'Hello, world!')
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}

注意:检测出的编码是ascii,注意到还有个confidence字段,表示检测的概率是1.0(即100%)。

2.2对GBK编码的中文检测编码

>>> data = '离离原上草,一岁一枯荣'.encode('gbk')
>>> chardet.detect(data)
{'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}

注意:检测的编码是GB2312,注意到GBK是GB2312的超集,两者是同一种编码,检测正确的概率是74%,language字段指出的语言是'Chinese'

2.3对UTF-8编码检测编码

>>> data = '离离原上草,一岁一枯荣'.encode('utf-8')
>>> chardet.detect(data)
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

2.4对日文检测编码

>>> data = '最新の主要ニュース'.encode('euc-jp')
>>> chardet.detect(data)
{'encoding': 'EUC-JP', 'confidence': 0.99, 'language': 'Japanese'}

总结:用chardet检测编码,使用简单。获取到编码后,再转换为str 

猜你喜欢

转载自blog.csdn.net/zyckhuntoria/article/details/81132598