python chardet


chardet:字符編碼檢測工具

字符串編碼一直是使人很是頭疼的問題,尤爲是咱們在處理一些不規範的第三方網頁的時候。雖然Python提供了Unicode表示的strbytes兩種數據類型,而且能夠經過encode()decode()方法轉換,可是,在不知道編碼的狀況下,對bytesdecode()很差作。html

對於未知編碼的bytes,要把它轉換成str,須要先「猜想」編碼。猜想的方式是先收集各類編碼的特徵字符,根據特徵字符判斷,就能有很大機率「猜對」。redis

固然,咱們確定不能從頭本身寫這個檢測編碼的功能,這樣作費時費力。chardet這個第三方庫正好就派上了用場。用它來檢測編碼,簡單易用。api


安裝:
  pip install chardet
  
官方文檔     :  https://chardet.readthedocs.io/en/latest/
更多       :  https://pypi.org/project/chardet/
支持的編碼    :  https//chardet.readthedocs.io/en/latest/supported-encodings.html
chardet module :  https://chardet.readthedocs.io/en/latest/api/modules.html

 

 

使用import urllibimport chardetrawdata =urllib.urlopen('http://yahoo.co.jp/').read()chardet.detect(rawdata)>>:{'encoding':'EUC-JP','confidence':0.pp}import redisrds = redis()rds.set('user_info','這是一串不怎麼何時存入不知道誰存入,什麼狀況下的字符串')user_info = rds.get('user_info')chardet.detect(user_info)>>{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}{"encoding":"字符編碼","confidence":"檢測機率,最大爲1,即100%,最小爲"}
相關文章
相關標籤/搜索