当前位置: 首页 > 图灵资讯 > 行业资讯> python如何查看字符集

python如何查看字符集

来源:图灵python
时间: 2025-01-08 14:54:52

python查看字符集的方法:可以利用第三方库chardet来进行判断。通过在命令行下执行【pip install chatdet】命令来安装chardet。使用方法如:【chardet.detect(b'Hello, world!')】。

Python利用第三方库chardet判断字符集。

(推荐教程:Python入门教程)

如果安装了Anaconda,chardet就已经可用了。否则,需要在命令行下通过pip安装:

$pipinstallchardet

当我们拿到一个bytes时,就可以对其检测编码。用chardet检测编码,只需要一行代码:

>>>chardet.detect(b'Hello,world!')
{'encoding':'ascii','confidence':1.0,'language':''}

检测出的编码是ascii,注意到还有个confidence字段,表示检测的概率是1.0(即100%)。

对UTF-8编码进行检测:

>>>data='离离原上草,一岁一枯荣'.encode('utf-8')
>>>chardet.detect(data)
{'encoding':'utf-8','confidence':0.99,'language':''}

用chardet检测编码,使用简单。获取到编码后,再转换为str,就可以方便后续处理。