python字符串编码识别模块chardet简单应用

732次阅读  |  发布于5年以前

python的字符串编码识别模块(第三方库):

官方地址: http://pypi.python.org/pypi/chardet



    import chardet
    import urllib

    # 可根据需要,选择不同的数据
    TestData = urllib.urlopen('http://www.baidu.com/').read()
    print chardet.detect(TestData)

    # 运行结果:
    # {'confidence': 0.99, 'encoding': 'GB2312'}
    运行结果表示有99%的概率认为这段代码是GB2312编码方式。

    import urllib
    from chardet.universaldetector import UniversalDetector
    usock = urllib.urlopen('http://www.baidu.com/')
    # 创建一个检测对象
    detector = UniversalDetector()
    for line in usock.readlines():
    # 分块进行测试,直到达到阈值
    detector.feed(line)
    if detector.done: break
    # 关闭检测对象
    detector.close()
    usock.close()
    # 输出检测结果
    print detector.result

    # 运行结果:
    # {'confidence': 0.99, 'encoding': 'GB2312'}

应用背景,如果要对一个大文件进行编码识别,使用这种高级的方法,可以只读一部,去判别编码方式从而提高检测速度。如果希望使用一个检测对象检测多个数据,在每次检测完,一定要运行一下detector.reset()。清除之前的数据。

以上所述就是本文的全部内容了,希望大家能够喜欢。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8