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'u8fdcu7a0bu4e3bu673au5f3au8febu5173u95edu4e86u4e00u4e2au73b0u6709u7684u8fdeu63a5u3002'
aa = char_det(a)
print(aa)
应用场景:
web端返回的中文信息,将其解码成中文字符