編碼方法encoding()
描述
encode() 方法以指定的編碼格式編碼字符串,默認編碼為 'utf-8'。將字符串由string類型變成bytes類型。
對應的解碼方法:bytes decode() 方法。
語法
str.encode([encoding='utf-8'][,errors='strict'])
- str是表示需要編碼的字符串,並且是個string類型。
- encoding -- 可選參數,要使用的編碼方案,默認編碼為 'utf-8'。
- errors -- 可選參數,設置不同錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通過 codecs.register_error() 注冊的任何值。
返回值
該方法返回編碼后的字符串,它是一個 bytes 對象,這個字節對象是用於下面的解碼用的。
官方文檔解釋:
str.encode(encoding="utf-8", errors="strict")
Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
------------------------------------------------------------------------------------------------------------------------------------------------
解碼方法decode()
decode() 方法以 encoding 指定的編碼格式來解碼字符串。默認編碼規則是encoding=‘utf-8’
語法:
bytes.decode(encoding='UTF-8',errors='strict')
參數
bytes是由編碼方法encoding()編碼轉換過后得到的字符串的字節表示值。
encoding -- 解碼時要使用的編碼方案,如"UTF-8"。
errors -- 設置不同錯誤的處理方案。默認為 'strict',意為編碼錯誤引起一個UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通過 codecs.register_error() 注冊的任何值。
返回值:
該方法返回解碼后的字符串。
官方文檔解釋
bytes.decode(encoding="utf-8", errors="strict")bytearray.decode(encoding="utf-8", errors="strict")
Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
Note
Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.
Changed in version 3.1: Added support for keyword arguments.
其實編碼解碼的關系就是如下:
str->bytes:encode編碼 bytes->str:decode解碼
字符串通過編碼成為字節碼,字節碼通過解碼成為字符串。可以這樣解釋,編碼就是將字符串轉換成字節碼,涉及到字符串的內部表示。解碼就是將字節碼轉換為字符串,將比特位顯示成字符。
例如:
1 >>> text = '我是文本'
2 >>> text 3 '我是文本'
4 >>> print(text) 5 我是文本 6 >>> bytesText = text.encode() 7 >>> bytesText 8 b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
9 >>> print(bytesText) 10 b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
11 >>> type(text) 12 <class 'str'>
13 >>> type(bytesText) 14 <class 'bytes'>
15 >>> textDecode = bytesText.decode() 16 >>> textDecode 17 '我是文本'
18 >>> print(textDecode) 19 我是文本
例2
1 >>>text='我好嗎' 2 >>>byteText=text.encode('gbk') 3 >>>byteText 4 b'\xce\xd2\xba\xc3\xc2\xf0' 5 >>>strText=byteText.decode('gbk') 6 >>>strText 7 '我好嗎' 8 >>>byteText.decode('utf-8') 9 Traceback (most recent call last): 10 File "G:\softs\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code 11 exec(code_obj, self.user_global_ns, self.user_ns) 12 File "<ipython-input-11-f0ef1443f388>", line 1, in <module> 13 byteText.decode('utf-8') 14 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 0: invalid continuation byte
上面的第8行出現了錯誤,是由於文本text='我好嗎',是按照‘gbk’進行編碼的,而在解碼時是按照‘utf-8’的編碼規則進行的解碼,所以會導致解碼失敗,即‘utf-8’不能解碼‘gbk’編碼規則的字節。用相對應的解碼編碼規則來對字符進行處理。下面給出了幾條處理這種錯誤的方法供參考。
出現如下錯誤時:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 11126: illegal multibyte sequence
使用python的時候經常會遇到文本的編碼與解碼問題,其中很常見的一種解碼錯誤如題目所示,下面介紹該錯誤的解決方法,將‘gbk’換成‘utf-8’也適用。
(1)、首先在打開文本的時候,設置其編碼格式,如:open(‘1.txt’,encoding=’gbk’);
(2)、若(1)不能解決,可能是文本中出現的一些特殊符號超出了gbk的編碼范圍,可以選擇編碼范圍更廣的‘gb18030’,如:open(‘1.txt’,encoding=’gb18030’);
(3)、若(2)仍不能解決,說明文中出現了連‘gb18030’也無法編碼的字符,可以使用‘ignore’屬性進行忽略,如:open(‘1.txt’,encoding=’gb18030’,errors=‘ignore’);
(4)、還有一種常見解決方法為open(‘1.txt’).read().decode(‘gb18030’,’ignore’)
對於機器學習實戰第四章朴素貝葉斯一張代碼實現出現的解碼錯誤就用了上面的方法(4)解決了
1 def spamTest(): 2 docList=[];classList=[];fillText=[] 3 for i in range(1,26): 4 wordList=textParse(open('D:/machinelearning data/machinelearninginaction/Ch04/email/spam/%d.txt' % i,encoding='utf-8',errors='ignore').read()) 5 # print('%d word:'%i) 6 docList.append(wordList) 7 fillText.extend(wordList) 8 classList.append(1) 9 wordList = textParse(open('D:/machinelearning data/machinelearninginaction/Ch04/email/ham/%d.txt' % i,encoding='utf-8',errors='ignore').read()) 10 docList.append(wordList) 11 fillText.extend(wordList) 12 classList.append(0)
原文上面代碼出現錯誤是因為在解析ham文件夾文件23.txt時出現解碼錯誤,才導致整個文件運行不了,我們將文件打開的編碼方式統一換成'utf-8',並且忽略掉出現的錯誤便可以正常運行了
參考資料:
1,https://www.cnblogs.com/tingyugetc/p/5727383.html
2,https://blog.csdn.net/shijing_0214/article/details/51971734
