zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    深度学习中一些常用函数的偏导数
    C++ 隐式类型转换与类型转换函数
    Tensorboard数据(tfevents文件)格式解析及ofstream使用问题
    记一次由unordered_map引起的bug
    softmax数值溢出 与 xent-loss问题
    C++ 单独编译(separate compilation)与 模板的编译
    TensorFlow源码分析——Tensor与Eigen
    ubuntu16.04 docker tensorflow-gpu镜像使用
    vscode Ftp-sync插件报错问题: sync error: Error: Permission denied
    PHP加速之eaccelerator
  • 原文地址:https://www.cnblogs.com/sundawei7/p/11954195.html
Copyright © 2011-2022 走看看