溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python解碼后為什么會亂碼

發(fā)布時間:2020-07-07 16:40:23 來源:億速云 閱讀:149 作者:清晨 欄目:編程語言

這篇文章主要介紹python解碼后為什么會亂碼,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

字符串在Python內(nèi)部的表示是unicode編碼,在做編碼轉(zhuǎn)換時,通常需要以unicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。

decode的作用是將其他編碼的字符串轉(zhuǎn)換成unicode編碼,如str1.decode(‘gb2312’),表示將gb2312編碼的字符串str1轉(zhuǎn)換成unicode編碼。

encode的作用是將unicode編碼轉(zhuǎn)換成其他編碼的字符串,如str2.encode(‘utf-8’),表示將unicode編碼的字符串str2轉(zhuǎn)換成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

如果一個字符串已經(jīng)是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解碼后為什么會亂碼的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI