品易云推流 关闭
文章详情页
文章 > Python常见问题 > python解码后乱码的原因是什么?

python解码后乱码的原因是什么?

头像

yang

2020-05-18 15:09:132496浏览 · 0收藏 · 0评论

字符串在Python内部的表示是unicode编码,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘utf-8’),表示将unicode编码的字符串str2转换成utf-8编码。

代码如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: xulinjie time:2017/10/22
import urllib2

request=urllib2.Request(r'http://nhxy.zjxu.edu.cn/')
RES=urllib2.urlopen(request).read()
RES = RES.decode('gb2312').encode('utf-8')//解决乱码
wfile=open(r'./1.html',r'wb')
wfile.write(RES)
wfile.close()
print RES

如果一个字符串已经是unicode了,再进行解码则将出错,因此通常要对其编码方式是否为unicode进行判断,

isinstance(s, unicode)#用来判断是否为unicode。

最终可靠代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: xulinjie time:2017/10/22
import urllib2

request=urllib2.Request(r'http://nhxy.zjxu.edu.cn/')
RES=urllib2.urlopen(request).read()

if isinstance(RES, unicode):
    RES=RES.encode('utf-8')
else:
    RES=RES.decode('gb2312').encode('utf-8')

wfile=open(r'./1.html',r'wb')
wfile.write(RES)
wfile.close()
print RES

更多Python知识请关注Python自学网

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图