chardet是python的一个第三方编码检测模块,可以检测文件,XML等字符编码的类型。通过pip install chardet安装使用。
1.chardet
我们在处理一些不规范的第三方网页的时候,对于未知编码的bytes,要把它转换成str,需要先“猜测”编码。chardet这个第三方库正好就派上了用场了,使用它可以轻松地检测页面所使用的编码。
# -*- coding: utf-8 -*-
# @Time : 2022/5/1 10:01
# @File : chardetdemo.py
# @Software : PyCharm
import chardet
cs = '离离原上草,一岁一枯荣'
js = 'ジャパン'
ks = '널이렇게하게할수있었던사람이라면 널울리질않았을거야'
cs_ef = chardet.detect(cs.encode('GBK'))
js_ef = chardet.detect(js.encode('euc_jp'))
ks_ef = chardet.detect(ks.encode('euc_kr'))
print(cs_ef)
print(js_ef)
print(ks_ef)
运行结果:
{'encoding': 'GB2312', 'confidence': 0.7407407407407407, 'language': 'Chinese'}
{'encoding': 'EUC-JP', 'confidence': 0.99, 'language': 'Japanese'}
{'encoding': 'EUC-KR', 'confidence': 0.99, 'language': 'Korean'}
检测目标为中日韩美德五个网站编码方式。
# -*- coding: utf-8 -*-
# @Time : 2022/5/1 10:01
# @File : chardetdemo.py
# @Software : PyCharm
from chardet import detect
from urllib import request
urls = [
'https://www.sina.com.cn/',
'https://www.ntv.co.jp/pc/',
'http://www.inu.ac.kr',
'https://www.bundesregierung.de/breg-de',
'https://www.walmart.com'
]
for url in urls:
resp = request.urlopen(url)
print(url, detect(resp.read()))
运行结果:
https://www.sina.com.cn/ {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
https://www.ntv.co.jp/pc/ {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
http://www.inu.ac.kr {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
https://www.bundesregierung.de/breg-de {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
https://www.walmart.com {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
可见大部分网站都体现了国际化思想,使用了UTF-8字符集编码。
小结: 使用chardet检测编码非常容易,chardet支持检测中文、日文、韩文等多种语言。