• chardet


    about

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

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

    对于未知编码的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,GBKGB2312的超集,它们同属于一种编码。

    检测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))

    see also:https://chardet.readthedocs.io/en/latest/index.html | https://www.liaoxuefeng.com/wiki/1016959663602400/1183255880134144 | https://www.jianshu.com/p/d73c0017158c

  • 相关阅读:
    Java Bean validation specification...
    javascript压缩工具:YUI compressor
    CSS: Float a div on another div, Ex: Text caption on picture
    汉文博士 0.5.3.1944 测试版发布
    简单记事本程序java源码项目
    Windows计算机功能Java源码
    HighCharts 图表插件 自定义绑定 时间轴数据
    Windows Phone 8.1 新特性
    可自定义导航条功能案例ios项目源码
    自动计算尺寸列表功能案例ios源码
  • 原文地址:https://www.cnblogs.com/sundawei7/p/11954195.html
Copyright © 2020-2023  润新知