天天看點

Python 3.x 與Python 2.x 的不同點彙總筆記

          Python3.x 相對于Python2.x 有了些許改動,這樣在用最新版Python3學習那些經典的教程(通常都是Python2版本的),運作例子的時候總容易報錯,但是既然是新的版本就是對之前的版本有更新改進的,用新版本程式設計肯定會是大的趨勢,下面總結常見的差別内容。

         1.open(filename, 'w')函數

         Python2 中 open(filename,‘w’).write(content)

     Python3 如果編輯此句代碼,輸出的内容格式不正确,因為python3讀取的是bytes類型。如下載下傳的html檔案打開不能讀取到正常的文字内容。

應改為:open(filename,‘wb’).write(content)

格式知識擴充:

             "r"   以讀方式打開,隻能讀檔案,如果檔案不存在,會發生異常      

             "w" 以寫方式打開,隻能寫檔案,如果檔案不存在,建立該檔案

                                                    如果檔案已存在,先清空,再打開檔案

             "rb"   以二進制讀方式打開,隻能讀檔案,如果檔案不存在,會發生異常      

             "wb" 以二進制寫方式打開,隻能寫檔案,如果檔案不存在,建立該檔案

                                                    如果檔案已存在,先清空,再打開檔案

             "rt"   以文本讀方式打開,隻能讀檔案,如果檔案不存在,會發生異常      

             "wt" 以文本寫方式打開,隻能寫檔案,如果檔案不存在,建立該檔案

                                                    如果檔案已存在,先清空,再打開檔案

             "rb+"   以二進制讀方式打開,可以讀、寫檔案,如果檔案不存在,會發生異常      

             "wb+" 以二進制寫方式打開,可以讀、寫檔案,如果檔案不存在,建立該檔案

                                                    如果檔案已存在,先清空,再打開檔案

             2.      Python2 中xrange,  python3 中應将xrange 改為 range.

例如:

for i in range(0,30):
        url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)+'&n=1&nc=1361089515117&FORM=HYLH1'
        html = urllib.request.urlopen(url).read()
           

           3.     Python2 中子產品Beautifulsoup的調用。

             import beautifulsoup as Beautifulsoup   在 Python3 中應改為 bs4

舉個栗子:

from bs4 import BeautifulSoup
import re

doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print (soup.prettify())
           

           4.   在python3 中, print 應該為print(), () 裡為所有要輸出的内容。

           5.   Python3中 text =text.decode(‘utf-8)

代碼例子: 抓取Bing 搜尋背景圖

import urllib.request,re,sys,os
def get_bing_backphoto():
    if (os.path.exists('photos')== False):
        os.mkdir('photos')
    for i in range(0,30):
        url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx='+str(i)+'&n=1&nc=1361089515117&FORM=HYLH1'
        html = urllib.request.urlopen(url).read()
        if html == 'null':
            print( 'open & read bing error!')
            sys.exit(-1)
        html = html.decode('utf-8')
        reg = re.compile('"url":"(.*?)","urlbase"',re.S)
        text = re.findall(reg,html)
        #http://s.cn.bing.net/az/hprichbg/rb/LongJi_ZH-CN8658435963_1366x768.jpg
        for imgurl in text :
            right = imgurl.rindex('/')
            name = imgurl.replace(imgurl[:right+1],'')
            savepath = 'photos/'+ name
            urllib.request.urlretrieve(imgurl, savepath)
            print (name + ' save success!')
get_bing_backphoto()
           

              6.    Python2中的urllib 和urllib2 整合為urllib在python3中。

             調用子產品時:  import urllib.request

              7.    Python2 中的raw.input() 改為 input()

              8.   在抓取網頁内容時,python3如果按照python2的代碼編輯出現如下報錯:

                       Can’t use a string pattern on abytes-like object

                           可通過b’轉化資料類型,例:

                              url = “http://www.baidu.com”

                             html = urllib.request.urlopen(url).read()

                              url = re.findall( b’/song/dt’, html, re.M)