Python开发实战

Python 3 查看字符编码方法

2019-02-21  本文已影响0人  Young先生

查看字符编码,需要用到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': ''}

Tips:

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

欢迎大家访问我的博客:bigyoung.cn

欢迎大家关注我的公众号:


公众号二维码.jpg
上一篇 下一篇

猜你喜欢

热点阅读