python如何查看字符集

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

python如何查看字符集

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':''}