python如何查看编码

2025-12-02 0 75,159

python中可以使用chardet模块检测字符串/文件编码。

1、chardet下载与安装

下载地址:http://pypi.python.org/pypi/chardet

下载chardet后,解压chardet压缩包,直接将chardet文件夹放在应用程序目录下,就可以使用import chardet开始使用chardet了,也可以将chardet拷贝到Python系统目录下,这样你所有的python程序只要用import chardet就可以了。

python setup.py install

使用中,chardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式。

示例:

网页编码判断:

>>> import urllib
>>> rawdata = urllib.urlopen('http://www.google.cn/').read()
>>> import chardet
>>> chardet.detect(rawdata)
{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}

文件编码判断

import chardet
tt=open('c:\111.txt','rb')
ff=tt.readline()
#这里试着换成read(5)也可以,但是换成readlines()后报错
enc=chardet.detect(ff)
print enc['encoding']
tt.close()

更多Python知识请关注Python视频教程栏目。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 常见问题 python如何查看编码 https://www.zhiup.top/7195.html

相关