python3 編解碼常見操作(codecs, url編解碼, soup例項化報錯)
codecs是encoders和decoders的縮寫。
codecs模組為我們解決的字元編碼的處理提供了lookup方法,它接受一個字元編碼名稱的引數,並返回指定字元編碼對應的codecs.CodecInfo 物件,該物件包含了 encoder、decoder、StreamReader和StreamWriter的函式物件和類物件的引用。為了簡化對lookup方法的呼叫, codecs還提供了getencoder(encoding)、getdecoder(encoding)、getreader(encoding)和 getwriter(encoding)方法;進一步,簡化對特定字元編碼的StreamReader、StreamWriter和 StreamReaderWriter的訪問,codecs更直接地提供了open方法,通過encoding引數傳遞字元編碼名稱,即可獲得對 encoder和decoder的雙向服務。
這個模組的強大之處在於它提供了流的方式來處理字串編碼,當處理的資料很多時,這種方式很有用。
你可以使用IncrementalEncoder和IncrementalDecoder,但是強烈建議使用StreamReader和StreamWriter,因為使用它們會大大簡化你的程式碼。
例如,有一個test.txt的檔案,它的編碼為gbk,現在我需要將它的編碼轉換為utf8,可以編寫如下程式碼:
- #coding:utf-8
- import codecs
- # 開啟檔案 如果此處用codecs.open()方法開啟檔案,就不用建立reader和writer
- fin = open('test.txt', 'r')
- fout = open('utf8.txt'
- # 獲取 StreamReader
- reader = codecs.getreader('gbk')(fin)
- # 獲取 StreamWriter
- writer = codecs.getwriter('utf8')(fout)
- din = reader.read(10)
- while din:
- writer.write(din)
- din = reader.read(10)
Python3的URL編碼解碼
最近在用python3比較強大的Django開發web的時候,發現一些url的編碼問題,在瀏覽器提交請求api時,如果url中包含漢子,就會被自動編碼掉。呈現的結果是 ==> %xx%xx%xx。如果出現3個百分號為一個原字元則為utf8編碼,如果2個百分號則為gb2312編碼。下面為大家演示編碼和解碼的程式碼。
編碼
from urllib.parse import quote
text = quote(text, 'utf-8')
解碼
from urllib.parse import unquote
text = unquote(text, 'utf-8')
python3的自動網址拼接----urljoin
from urllib.parse import urljoin
new_url = "/item/百度百科:本人詞條編輯服務/22442459?bk_fr=pcFooter"
page_url = "https://baike.baidu.com/item/企業家/1243741"
new_full_url = urljoin(page_url, new_url)
--> new_full_url ---> https://baike.baidu.com/item/百度百科:本人詞條編輯服務/22442459?bk_fr=pcFooter
python3 中 BeautifulSoup soup例項化吧報錯
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
執行報錯:You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored.
原因:python3 預設的編碼是unicode, 再在from_encoding設定為utf8, 會被忽視掉,去掉from_encoding="utf-8"這一個好了。
正確寫法:soup = BeautifulSoup(unquote(html_cont, 'utf-8'), 'html.parser')