Python玩耍Python生活不易 我用python

7.python3编码问题

2016-07-29  本文已影响256人  KaelQ

1.python 的文本数据和二进制数据

方法 含义
str.encode('gbk') 将默认的utf-8编码成gbk编编码,类型转为bytes
bytes.decode('gbk') 将gbk的编码转化为默认的utf-8编码,类型转为string

如图:

转换图
# 忽略转换过程中无法转换的字符
str.encode('gbk','ignore')

2.检测所读数据是什么编码

2.1 安装

pipinstall chardet

2.2 使用

import chardet
import urllib.request
code=urllib.request.urlopen("http://tieba.baidu.com/").read()
print(chardet.detect(code))

结果为:


result

这里检测出百度贴吧首页为GB2312编码,概率为0.99。这样基本确定这个页面的编码是GB2312了。

上一篇 下一篇

猜你喜欢

热点阅读