python 常用模块介绍

chardet

github: https://github.com/chardet/chardet
官网:http://pypi.python.org/pypi/chardet


chardet是一款用于字符串编码方式识别模块,这个模块是python的第三方库,所以需要进行安装。

  1. 安装

    • 直接下载安装包方式安装
      直接下载whl文件,放在python安装根目录\Lib\site-packages下,确保可以被python正确引用。
    • 下载chardet源码方式,进行手动安装
      sudo apt-get install pip #安装pip
      sudo apt-get install python-setuptools #安装setuptools
      wget https://pypi.python.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz#md5=7dd1ba7f9c77e32351b0a0cfacf4055c  #下载chardet源码,也可以手动下载
      tar zxvf chardet-3.0.4.tar  # 解压文件到当前目录
      cd chardet-3.0.4
      sudo python setup.py install # 进行安装
      
  2. 实例:
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'}  

高级用法

    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'}  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值