python查看字符集的方法:可以利用第三方库chardet来进行判断。通过在命令行下执行【pip install chatdet】命令来安装chardet。使用方法如:【chardet.detect(b'Hello, world!')】。
Python利用第三方库chardet判断字符集。
(推荐教程:Python入门教程)
如果安装了Anaconda,chardet就已经可用了。否则,需要在命令行下通过pip安装:
当我们拿到一个bytes时,就可以对其检测编码。用chardet检测编码,只需要一行代码:
1 2 | >>> chardet.detect(b 'Hello, world!' )
{ 'encoding' : 'ascii' , 'confidence' : 1.0, 'language' : '' }
|
检测出的编码是ascii,注意到还有个confidence字段,表示检测的概率是1.0(即100%)。
对UTF-8编码进行检测:
1 2 3 | >>> data = '离离原上草,一岁一枯荣' .encode( 'utf-8' )
>>> chardet.detect(data)
{ 'encoding' : 'utf-8' , 'confidence' : 0.99, 'language' : '' }
|
用chardet检测编码,使用简单。获取到编码后,再转换为str,就可以方便后续处理。