python检查编码方式chardet用法

 时间:2026-02-14 04:12:32

1、使用pip安装chardet包

pip install chardet

python检查编码方式chardet用法

2、打开python开发工具IDLE,新建‘chardetest.py’文件,并写代码如下:

import chardet

a = '你好'

b = 'nihao'

print (chardet.detect(a))

print (chardet.detect(b))

python检查编码方式chardet用法

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

python检查编码方式chardet用法

4、默认编码方式编码字符串,修改代码如下:

import chardet

a = '你好'

b = 'nihao'

a1=a.encode()

b1=b.encode()

print (chardet.detect(a1))

print (chardet.detect(b1))

python检查编码方式chardet用法

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

python检查编码方式chardet用法

6、解码可以使用下面代码

import chardet

a = '你好'

b = 'nihao'

a1=a.encode()

b1=b.encode()

ac=chardet.detect(a1)

print (a1.decode(ac['encoding']))

ac是一个字典类型,就是上一步打印出来的内容

python检查编码方式chardet用法

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

python检查编码方式chardet用法

  • Windows10系统中【全选键】的使用方法?
  • vivoX9手机怎么设置指纹解锁?
  • 七读免费小说怎么删除阅读记录
  • Windows XP 如何设置打印机纸张的大小
  • 辣椒炒鳅鱼怎么做好吃?
  • 热门搜索
    土豆炖鸡块的家常做法 烤鸡腿的做法 五红汤的做法和功效 血糖高怎么办 元稹怎么读 芒果慕斯蛋糕的做法 笄怎么读 虎皮辣子的做法 王者荣耀健康系统怎么解除 凉拌苦瓜的做法