Python3查看字符编码方法

, Read in about 1 min

Posted by Ryen on Thursday, March 4, 2021
With final update in December 26,2023

本文总阅读量

查看字符编码,需要用到chardet模块

一、查看网页编码

#coding=utf-8
import urllib . request
import chardet
url = 'http://www.baidu.com'
a = urllib . request . urlopen ( url )
encode = chardet . detect ( a . read ( ) )
print ( encode [ 'encoding' ] )

二、查看文件内容编码

#假设存在一个a.txt的文件
f = open ( 'a.txt' , 'rb' )
print ( chardet . detect ( f . read ( 100 ) ) )

三、查看某个字符串编码

import chardet
s = '张三'
print ( chardet . detect ( str . encode ( s ) ) )
输出信息: { 'encoding' : 'utf-8' , 'confidence' : 0.7525 , 'language' : '' }

补充:

chardet . detect 在查看字符串传的编码时,必须要把字符串 encode后,才能查看当前字符串编码格式

「真诚赞赏,手留余香」

Ryen's Blog

真诚赞赏,手留余香

使用微信扫描二维码完成支付