查看字符编码,需要用到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'])
1 2 3 4 5 6 7 8 | #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)))
1 2 3 4 | #假设存在一个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': ''}
1 2 3 4 5 | import chardet s = '张三' print(chardet.detect(str.encode(s))) 输出信息:{'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''} |
Tips:
chardet.detect 在查看字符串传的编码时,必须要把字符串encode后,才能查看当前字符串编码格式
1 2 | chardet.detect 在查看字符串传的编码时,必须要把字符串encode后,才能查看当前字符串编码格式 |