python 字符串编码检测
chardet 模块
使用通用编码检测器库的最简单方法是使用detect函数,
detect函数有一个参数, 即非 unicode 字符串。
它返回一个字典, 其中包含自动检测的字符编码和从0到1的置信度。
import chardet
def char_det(det_str: str)->str:
"""
对ASCII编码,进行解码
:param det_str: 待检测字符
:return:
"""
res_dict = chardet.detect(det_str)
if res_dict.get('encoding') == 'ascii':
return det_str.decode('unicode_escape')
else:
return det_str
if __name__ == '__main__':
a = b'\u8fdc\u7a0b\u4e3b\u673a\u5f3a\u8feb\u5173\u95ed\u4e86\u4e00\u4e2a\u73b0\u6709\u7684\u8fde\u63a5\u3002'
aa = char_det(a)
print(aa)
应用场景:
web端返回的中文信息,将其解码成中文字符