python chardet_Python - chardet

about

chardet提供自动检测字符编码的功能。

当我们在处理一些不规范的网页的时候。虽然Python提供了Unicode表示的str和bytes两种数据类型,并且可以通过encode()和decode()方法转换,但是在不知道编码的情况下,对bytes做decode()容易失败。

对于未知编码的bytes,要把它转换成str,那么就需要先“猜测”编码。猜测的方式是先收集各种编码的特征字符,根据特征字符判断,就能有很大概率“猜对”。

当然,我们肯定不能从头自己写这个检测编码的功能,这样做费时费力。chardet这个第三方库正好就派上了用场。用它来检测编码,简单易用。

下载

pip install chardet

使用前需先引入。

Usage

chardet.detect

detect()函数接受一个参数,一个非unicode字符串。它返回一个字典,其中包含自动检测到的字符编码和从0到1的可信度级别。

response = requests.get('https://www.baidu.com')

print(chardet.detect(response.content)) # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

返回的字典中:

encoding:表示字符编码方式。

confidence:表示可信度。

language:语言。

大文件编码判断

上面的例子,是一下子读完,然后进行判断,但这不适合大文件。

因此,这里我们选择对读取的数据进行分块迭代,每次迭代出的数据喂给detector,当喂给detector数据达到一定程度足以进行高准确性判断时,detector.done返回True。此时我们就可以获取该文件的编码格式。

import requests

from chardet.universaldetector import UniversalDetector

url = 'https://chardet.readthedocs.io/en/latest/index.html'

response = requests.get(url=url, stream=True)

detector = UniversalDetector()

for line in response.iter_lines():

detector.feed(line)

if detector.done:

break

detector.close()

print(detector.result) # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

至于response.iter_lines()不安全,我们不管,这里只是用来将数据喂给detector提高准确率。

检测gbk

import chardet

msg = '马上2020年奔小康,我问左手:房子、车子、票子、女人,你还有哪样没达标!'.encode('GBK')

print(chardet.detect(msg)) # {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}

注意,检测到的编码是GB2321,relax,GBK是GB2312的超集,它们同属于一种编码。

检测utf-8

import chardet

msg = '左手说:你膨胀了啊?你他娘的哪样达标了?'.encode('UTF-8')

print(chardet.detect(msg)) # {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

检测日文

import chardet

msg = 'おじさん、こんなふうにならないで'.encode('euc-jp') # {'encoding': 'EUC-JP', 'confidence': 1.0, 'language': 'Japanese'}

print(chardet.detect(msg))

欢迎斧正,that's all

see also:| |

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值