python 中chardet用法

# coding=utf-8

import os
import chardet

root = os.getcwd()
path = os.path.sep.join((root, "lst.txt"))
with open(path, "rb") as f:
    data = f.read()
    en = chardet.detect(data)
    print(data.decode(en["encoding"]))

判断大文件编码格式,参考:https://www.cnblogs.com/Neeo/articles/11528011.html

大文件编码判断

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

因此,这里我们选择对读取的数据进行分块迭代,每次迭代出的数据喂给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': ''}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值