chardet:字符编码检测工具
字符串编码一直是使人很是头疼的问题,尤为是咱们在处理一些不规范的第三方网页的时候。虽然Python提供了Unicode表示的str
和bytes
两种数据类型,而且能够经过encode()
和decode()
方法转换,可是,在不知道编码的状况下,对bytes
作decode()
很差作。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%,最小为"}