chardet是一個非常優秀的編碼識別模塊。
chardet 是python的第三方庫,需要下載和安裝,放在python安裝根目錄\Lib\site-packages下面
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'}
應用背景,如果要對一個大文件進行編碼識別,使用這種高級的方法,可以只讀一部,去判別編碼方式從而提高檢測速度。
參考資料:http://cache.baiducontent.com/c?m=9f65cb4a8c8507ed4fece7631046893b4c4380146d96864968d4e414c42246071c35bff37d651304d2d82f2747f41802bded602571507be9dad58249d7be942d2d9c6269304a8903599543f2975125b071ca09a9f94ea1&p=9e3f865bc5904ead08e2947d0f5da5&newp=9234c64ad48309f30cbd9b7e0e148b231610db2151d7d3146b82c825d7331b001c3bbfb423221b01d7c6776302aa4856e8f732743c0821a3dda5c91d9fb4c57479c86f6824&user=baidu&fm=sc&query=python+chardet&qid=a082077700050a7d&p1=1