• 技术文章 >常见问题 >Python常见问题

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

    yangyang2020-05-18 15:09:13原创2449

    字符串在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编码。

    代码如下:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    #!/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。

    最终可靠代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    #!/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自学网

    专题推荐:python
    上一篇:如何用Python编写一副扑克牌? 下一篇:如何用python画六边形?

    相关文章推荐

    • 如何把python文件做成exe文件• Python使用什么划分语句块?• 怎么查看python.exe文件在哪?• 如何用Python画一颗小树?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网