品易云推流 关闭
文章详情页
文章 > Python高级 > python如何查看字符集

python如何查看字符集

头像

FXL

2020-08-12 10:09:083881浏览 · 0收藏 · 0评论

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

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

(推荐教程:Python入门教程

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

$ pip install chardet

当我们拿到一个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,就可以方便后续处理。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图