python检查编码方式chardet用法

2025-04-24 18:22:47

1、使用pip安装chardet包pip install chardet

python检查编码方式chardet用法

2、打开python开发工具IDLE,新建‘chardetest.py’文件,并写代码如下:import chardeta = '你好'b = 'nihao'print (chardet.detect(a))print (chardet.detect(b))

python检查编码方式chardet用法

3、F5运行程序,程序出错,这是因为chardet.detect时检查编码之后bytes格式的编码方式,不能检查str

python检查编码方式chardet用法

4、默认编码方式编码字腿发滏呸符串,修改代码如下:import chardeta = '你好'b = 'nihao'a1=a.encode()b1=b.e荏鱿胫协ncode()print (chardet.detect(a1))print (chardet.detect(b1))

python检查编码方式chardet用法

5、F5运行程序,打印出编码方式,注意英文字母还是ascii编码

python检查编码方式chardet用法

6、解码可以使用下面代码import chardeta = '你好'b = 'nihao'a1=a.enc泠贾高框ode()b1=b.encode()ac=chardet.detect(a1)print (a1.decode(ac['encoding']))ac是一个字典类型,就是上一步打印出来的内容

python检查编码方式chardet用法

7、F5运行代码,正确解码成字符串如下图

python检查编码方式chardet用法
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢