Python 編碼轉換與中文處理

來源:互聯網
上載者:User

標籤:recent   search   ade   odi   匹配   com   字元   safari   nic   

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 編碼轉換與中文處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.