Python3 编码问题: 怎么将Unicode转中文,以及GBK乱码ÖйúÉÙÊýÃñ×åÌØÉ«´åÕ¯
生活随笔
收集整理的這篇文章主要介紹了
Python3 编码问题: 怎么将Unicode转中文,以及GBK乱码ÖйúÉÙÊýÃñ×åÌØÉ«´åÕ¯
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
- 原理:
- 1. 案例:
- 2. 結果對比:
- 案例2,\xe5\x8f\xa4\xe8\xbf\xb9編碼
- 出現(xiàn)GBK無法編譯
- 文件讀寫操作codecs.open
原理:
如果***type(text) is bytes***, 那么text.decode('unicode_escape')
如果type(text) is str,
那么text.encode(‘latin1’).decode(‘unicode_escape’)
1. 案例:
*
#coding=utf-8 import requests,re,json,traceback from bs4 import BeautifulSoupdef qiushibaike():content = requests.get('http://baike.baidu.com/city/api/citylemmalist?type=0&cityId=360&offset=1&limit=60').contentsoup = BeautifulSoup(content, 'html.parser')print(soup.prettify()) #.decode("unicode_escape")#目前soup.prettify()為strnew=soup.prettify().encode('latin-1').decode('unicode_escape')#.dencode('latin-1').encode('latin-1').decode('unicode_escape')print(new)if __name__=='__main__':qiushibaike()2. 結果對比:
案例2,\xe5\x8f\xa4\xe8\xbf\xb9編碼
\xe5\x8f\xa4\xe8\xbf\xb9編碼處理
userInputTag=["\xe5\x8f\xa4\xe8\xbf\xb9","\xe5\xbb\xba\xe7\xad\x91"] print(userInputTag[0].encode('latin-1').decode('utf-8'))結果:
古跡完成轉化
出現(xiàn)GBK無法編譯
另外爬取時,網(wǎng)站代碼出現(xiàn)GBK無法編譯python3,如出現(xiàn)如下:
<h1>?D1úéùêy??×?ì?é?′??ˉ[6]</h1>示例:
#coding=utf-8 import requests #共有6頁,首頁為空不為6 for i in range(6):if i==0:url='http://www.tcmap.com.cn/list/zhongguoshaoshuminzutesecunzhai.html'else:url='http://www.tcmap.com.cn/list/zhongguoshaoshuminzutesecunzhai'+str(i)+'.html'response=requests.get(url)print(type(response))#如需成功編譯,在.TEXT下面增加#號部分 html=response.text #.encode('latin-1').decode('GBK')print(html)文件讀寫操作codecs.open
python 文件讀寫時用open還是codecs.open
案例:當我們需要寫入到TXT中的過程中
代替這繁瑣的操作就是codecs.open,例如
import codecs
fw = codecs.open(‘test1.txt’,’a’,’utf-8’)
fw.write(line2)
不會報錯,說明寫入成功。這種方法可以指定一個編碼打開文件,使用這個方法打開的文件讀取返回的將是unicode。寫入時,如果參數(shù) 是unicode,則使用open()時指定的編碼進行編碼后寫入;如果是str,則先根據(jù)源代碼文件聲明的字符編碼,解碼成unicode后再進行前述 操作。相對內置的open()來說,這個方法比較不容易在編碼上出現(xiàn)問題。
總結
以上是生活随笔為你收集整理的Python3 编码问题: 怎么将Unicode转中文,以及GBK乱码ÖйúÉÙÊýÃñ×åÌØÉ«´åÕ¯的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 暖通毕业设计总结系列1——设计手段
- 下一篇: python多线程详解_Python多线