导语:
本文主要介绍了关于python解码后乱码的原因是什么?的相关知识,希望可以帮到处于编程学习途中的小伙伴
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代码存储在哪里08/30
- ♥ Python文件读取()方法10/20
- ♥ Python 中的描述符11/03
- ♥ python如何设置路径08/18
- ♥ 判断python模块中全局变量的赋值10/25
- ♥ python如何控制输入范围08/16
内容反馈