Python 編碼轉換與中文處理
python 中的 unicode是讓人很困惑、比較難以理解的問題. utf-8是unicode的一種實現方式,unicode、gbk、gb2312是編碼字符集.
decode是將普通字符串按照參數中的編碼格式進行解析,然後生成對應的unicode對象
寫python時遇到的中文編碼問題:
? /test sudo vim test.py
#!/usr/bin/python
#-*- coding:utf-8 -*-
def weather():
import time
import re
import urllib2
import itchat
#模擬瀏覽器
hearders = "User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
url = "https://tianqi.moji.com/weather/china/guangdong/shantou" ##要爬去天氣預報的網址
par = '(<meta name="description" content=")(.*?)(">)' ##正則匹配,匹配出網頁內要的內容
##創建opener對象並設置為全局對象
opener = urllib2.build_opener()
opener.addheaders = [hearders]
urllib2.install_opener(opener)
##獲取網頁
html = urllib2.urlopen(url).read().decode("utf-8")
##提取需要爬取的內容
data = re.search(par,html).group(2)
print type(data)
data.encode('gb2312')
b = '天氣預報'
print type(b)
c = b + '\n' + data
print c
weather()
? /test sudo python test.py
<type 'unicode'>
<type 'str'>
Traceback (most recent call last):
File "test.py", line 30, in <module>
weather()
File "test.py", line 28, in weather
c = b + '\n' + data
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
解決方法:
? /test sudo vim test.py
#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
reload(sys)
# Python2.5 初始化後會刪除 sys.setdefaultencoding 這個方法,我們需要重新載入
sys.setdefaultencoding('utf-8')
def weather():
import time
import re
import urllib2
import itchat
#模擬瀏覽器
hearders = "User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
url = "https://tianqi.moji.com/weather/china/guangdong/shantou" ##要爬去天氣預報的網址
par = '(<meta name="description" content=")(.*?)(">)' ##正則匹配,匹配出網頁內要的內容
##創建opener對象並設置為全局對象
opener = urllib2.build_opener()
opener.addheaders = [hearders]
urllib2.install_opener(opener)
##獲取網頁
html = urllib2.urlopen(url).read().decode("utf-8")
##提取需要爬取的內容
data = re.search(par,html).group(2)
print type(data)
data.encode('gb2312')
b = '天氣預報'
print type(b)
c = b + '\n' + data
print c
weather()
測試後:
? /test sudo python test.py
<type 'unicode'>
<type 'str'>
天氣預報
汕頭市今天實況:20度 多雲,濕度:57%,東風:2級。白天:20度,多雲。 夜間:晴,13度,天氣偏涼了,墨跡天氣建議您穿上厚些的外套或是保暖的羊毛衫,年老體弱者可以選擇保暖的搖粒絨外套。
Python 編碼轉換與中文處理