《Python核心編程》第三版 讀書筆記

“一個不成熟男子的標誌是爲了某種事業英勇地死去,一個成熟男子的標誌是爲了某種事業卑微地活着。”

                                                                                                     -------<麥田裏的守望者>

小的時候總以爲自己長大會變成很厲害的人。後來知道自己沒希望了,那就變成成功圓滿的人也可以啊。
再後來覺得,即使普通,只要度過快樂幸福的人生就好。
再後來,發現只要活着就行。對自己提出要求,只會令人痛苦。

                                                                                              -----------作者:崇九


知乎上看到的,不管如何,我被生了下來,家境也不優越,父母仍需奔波,已然不可能孑然一生, 第一次讀<麥田裏的守望者>在初中,感謝那些年無知的自我,不會過早發現世間的祕密.   ^_^,加油,生活.   2019.9.1

第一章,正則表達式

  1. 簡介,動機:

  2. 特殊符號和字符

    1. 使用擇一匹配符號匹配多個正則表達式模式,(|)
    2. 匹配任意單個字符(.)
    3. 從字符串起始或者結尾或者單詞邊界匹配。(^ $)
    4. 創建字符集,([])
    5. 限定範圍與否定,([^], -)
    6. 使用閉包操作符實現存在性和頻數(*,+,?)
    7. 使用圓括號指定分組
    8. 表示字符集的特殊字符(\w \d)
    9. 擴展表示法
  3.  正則表達式和Python語言

    1. re模塊,核心函數和方法
    2. 使用compile函數編譯 正則表達式。
    3. 匹配對象已及group()和groups()
    4. 使用match()方法匹配字符串
    5. 使用search()在一個字符串中查找模式(搜索與匹配的對比)。
    6. # from 包名 import 模塊名
      import re
      # match(模式,字符串),開始位置匹配
      m = re.match('foo','foo')
      # 如果 m 不爲空
      if m is not None: print(m.group()) #foo
      m = re.match('foo','lrl')
      if m is not None: print(m.group()) #
      m = re.match('foo', 'food on the table')
      print('長串:'+m.group()) #foo
      m = re.match('foo', 'sefoo')
      if m is not None:print(m.group()) #
      #search,任意位置搜索。
      m = re.search('foo','sefoo' )
      if m is not None:print(m.group()) # foo
    7. 匹配多個字符
    8. 匹配任何單個字符
    9. 創建字符集
    10. #匹配多個字符串
      bt = 'bat|bet|bit'
      bt = re.compile(bt)
      m = re.match(bt,'bat')
      if m is not None: print(m.group())
      m = re.match('bat|bet|bit', 'bat')
      if m is not None:print(m.group()) 
      #匹配任何單個字符
      anyand = '.end'
      m = re.match(anyand, 'bend')
      if m is not None:print(m.group())
      # end
      m = re.match(anyand, 'end')
      if m is not None:print(m.group())
      #
      m = re.match(anyand, '\nend')
      if m is not None:print(m.group())
      #
      m = re.search('.end', 'the end.')
      if m is not None:print(m.group())
      # end
      #搜索小數點
      patty= '3.14'
      pi_patt = '3\.14'
      m = re.match(pi_patt, '3.14')
      if m is not None:print(m.group()) #3.14
      m = re.match(patty,'3014')
      if m is not None:print(m.group()) #3014
      
      #創建字符集[]
      m = re.match('[li][rui][long]','lrl')
      if m is not None:print(m.group()) #lrl
      
      m = re.match('[a-z]+','aaaa' )
      if m is not None:print(m.group()) #aaaa
    11. 重複,特殊字符及分組
    12. 重複,特殊字符以即分組
      m = re.match(patt, '[email protected]')
      if m is not None: print(m.group()) #[email protected]
      m = re.match(patt, '[email protected]') #[email protected]
      if m is not None: print(m.group())
      
      m = re.match('\w\w\w-\d\d\d', 'abc-xyz') #
      if m is not None: print(m.group())
      
      x = 1;
      y = 2;
      #變量的直接轉換
      (x,y) =( y,x)
      print(x)
      print(y)
      
      m = re.match('(\w\w\w)-(\d\d\d)','abc-123')
      #返回匹配串
      if m is not None: print(m.group())
      #返回子組
      if m is not None:print(m.group(1))
      if m is not None:print(m.group(2))
      if m is not None: print(m.groups())
      #group()通常用於以普通的方式顯示所有的匹配部分
      #groups()通常獲取一個包含所有匹配子字符串的元組。
      m = re.match('(ab)', 'ab')
      def pring(m):
          print('輸出group()')
          if m is not None: print(m.group())
          print('輸出groups()+以元組方式輸出:')
          if m is not None: print(m.groups())
          print("輸出group(i)")
          if m is not None: print(m.group(1))
      pring(m)
      m = re.match("(a)(b)", 'ab')
      pring(m)
    13. 匹配字符串的起始和結尾已及單詞邊界
    14. #匹配字符串的起始位置和結尾已及單詞邊界
      def pri(m):
          if m is not None: print(m.group())
      
      m = re.search('^The',"The end.")
      pri(m)
      m = re.search('^The',"sThe end.") # 無值
      pri(m)
      #\b用於匹配單詞邊界。\B用與不匹配邊界。
      m = re.search(r'\bthe', 'bite the dog')
      pri(m)
      m = re.search(r'\bthe' , "btthe")#無值
      pri(m)
      m = re.search(r'\Bthe', 'bithe dog') #the
      pri(m)
      
    15. 使用findall()和finalter()查找每一次出現的位置
    16. #使用findall()和findlter()查找每一次出現的位置
      #findall()返回一個數組,l類似一search
      def prfin(m):
          print(m)
      m = re.findall('car', 'car')
      prfin(m)
      m = re.findall('car','scar')#['car']
      prfin(m)
      m = re.findall('car' , 'carry the bacar the car')#['car', 'car', 'car']
      prfin(m)
      s = "This and that."
      #re.I忽略大小寫 r'意思爲不轉義
      m = re.findall(r'(th\w+) and (th\w+)', s, re.I) #[('This', 'that')]
      print(m)
      print("finditer的使用方式!!")
      print("finditer的使用方式!")
      m = [g.groups() for g in re.finditer(r'(th\w+) and (th\w+)', s, re.I)]
      print(m)
    17. 使用sub()和subn()搜索和轉換
    18. #使用sub()和subn()搜索與替換,將正則表達式所匹配的進行替換。用來替換的部分通常是一個字符串。
      #把sub(要替換的串,替換的串,替換後的子串)
      m = re.sub('X','Mr. Smith', 'attn: X\n\nDear X,\n')
      print(m)
      # attn: Mr. Smith
      #
      # Dear Mr. Smith,
      #把sub(要替換的串,替換的串,替換後的子串)返回替換的總數
      m = re.subn("X",'Mr.Smith','attn: X\n\nDear X,\n')#('attn: Mr.Smith\n\nDear Mr.Smith,\n', 2)
      print(m)
      m = re.sub('[ae]', 'X', 'abcdef')#XbcdXf
      print(m)
      

       

    19. 在限定模式上使用split()分隔字符串
    20. #在限定模式上使用split()分割字符串
      m = re.split(":", 'sta1:sta2:sta3')
      print(m)
      DATA = {
          'SHNAG HAI,144',
          'GUANGZHOU,522',
          'LINGXIA,455'
      }
      for lam in DATA:
          print(re.split(",",lam))
      # ['LINGXIA', '455']
      # ['GUANGZHOU', '522']
      # ['SHNAG HAI', '144']

       

    21. 擴展符號

    22. #擴展符號:
      #(?i)忽略大小寫匹配
      m = re.findall(r'(?i)yes','yes? Yes. YES!!')#['yes', 'Yes', 'YES']
      print(m)
      m = re.findall(r'(?i)th\w+','The quickest way is throgh this tunnel.')#['The', 'throgh', 'this']
      print(m)
      
      m = re.findall(r'(?im)(^th[\w]+)', """
          This line is the fie ,
          another line,
          that line ,it's basd th
          """)
      print(m)

       

    23. 一些正則表達式的實例:

    24. 在Linux下輸入who獲取當前系統的用戶信息:解析獲取到的信息,

    25. import os
      import re
      # 將系統指令的執行信息寫入f
      f = os.popen('who','r')
      for each in f:
      # split方法用於指定分隔符分割,each,retrip用於去除空格。\s表示空格\t表示製表符
         print re.split(r'\s\s+|\t', each.rstrip())
      f.close()
      
      
      
      
      [root@localhost pythonDemo.py]# python rewho.py
      ['root', 'tty1', '2019-07-29 10:52']
      ['root', 'pts/0', '2019-08-30 08:53 (192.168.36.1)']
      ['root', 'pts/1', '2019-08-30 10:17 (192.168.36.1)']
      ['root', 'pts/2', '2019-08-30 10:55 (192.168.36.1)']
      

       

    26. 用正則表達式練習的數據生成器(gendata.py)

    27. from random import randrange, choice
      # ascii_lowercase表示一個擁有26個小寫字母的序列集合。
      from string import ascii_lowercase as lc
      from sys import maxint
      from time import ctime
      #定義一個元組
      tlds = ('com', 'edu', 'net', 'org', 'gov')
      #生成第5行和第10之間的輸出,隨機整數使用xrange(randrange(i,j))
      for i in xrange(randrange(5,11 )):
          # 獲取的隨機整數範圍爲2的32次方。
          dtint = randrange(2**32)
          # 由獲取的隨進整數的得到一個日期。
          dtstr = ctime(dtint)
          # 獲取僞造郵件地址的登錄名爲4到7個字符
          llen = randrange(4, 8)
          # 隨機選擇4到7個小寫字母,將所有的字符連接成一個字符串。choice()函數的功能就是接受一個序列。
          # 然後返回該序列的隨機元素。生成用戶名 
          login = ''.join(choice(lc) for j in range(llen))
          # 郵件地址的主域名不超過12個字符。但至少要比登錄名一樣長。
          dlen = randrange(llen, 13)
          # 生成郵件地址主域名。
          dom = ''.join(choice(lc) for j in xrange(dlen))
          # 指定格式把信息輸出,
          print '%s::%s@%s.%s::%d-%d-%d' % (dtstr, login, dom, choice(tlds), dtint, llen, dlen)
          
      
      
      
      
      [root@localhost pythonDemo.py]# python genddata.py
      Tue Mar 19 22:30:43 1985::[email protected]::480090643-4-5
      Thu Jul 20 09:54:33 2084::[email protected]::3614896473-6-11
      Thu Jul  3 23:42:06 2059::[email protected]::2824472526-5-5
      Thu Dec  6 05:55:47 2096::[email protected]::4005582947-5-6
      Fri Mar 16 20:54:13 2001::[email protected]::984747253-7-8
      Fri Apr  2 23:51:47 1971::[email protected]::39455507-4-4
      Sun Jan 30 07:12:35 2056::[email protected]::2716413155-4-6
      Wed Jun 24 07:13:10 2026::[email protected]::1782256390-7-10
      Wed Jun  5 02:51:10 1974::[email protected]::139603870-5-8
      
      
      

       

    28. 匹配字符串:

    29. import re
      data = 'Thu Dec  6 05:55:47 2096::[email protected]::4005582947-5-6'
      patt = '^(\w{3})'
      m = re.match(patt, data)
      
      if m is not None:print(m.group())

       

    30.  

 

    1. 網路編程:

    2. 在服務器響應客戶端請求之前,必須執行一些初步的設置流程來爲之後的工作做準備。創建一個通信端點,能夠使服務器監聽請求。
    3. 套接字:計算機網絡的數據結構,任何類型的通行在開始之前,網絡應用程序必須創建套接字,可以將他們比電話擦孔,有兩種類型的套接字,基於文件(AF_UNIX)的和麪向網絡(AF_INEF)的。

    4. 總的來說Python只支持AF_UNIX,AF_NETLINK,AF_TICP和AF_INET家族,在所有的家族中AF_INET使用最廣泛。

    5. 套接字地址:主機-端口對,一個網絡地址由主機號和端口號組成。

    6. 面向連接的套接字和麪向無連接的套接字,

    7. 面向連接的套接字:提供可靠的不重複的序列化的數據交付,沒有記錄邊界,意外着每條消息可以拆分爲多個片段,且每天消息保證都可要到達目的地。即傳輸控制協議,創建TCP套接字,必須使用SOCK_STREAM 作爲套接字類型,TCP套接字的名字是SOCK_STREAM基於流套接字的其中一種表示。

    8. 無連接套接字:在傳輸的過程中不需要建立連接,在數據傳輸過程中無法保證他的順序性,可靠性和重複性。數據報保存了記錄邊界,消息是以整體發送的。主要有用戶數據報協議,使用SOCK_DGRAM作爲套接字,

  1. Python的網絡編程:

    1. socket()模塊:這個模塊中有一個socket()函數,該函數用於創建套機字對象,套接字也有自己的方法 集,這些方法可以實現基於套接字的網絡通行。

    2. socket()模塊函數,socket(socket_family(AF_UNIX\AF_INET),socket_type(SOCK_STREAM\SOCK_DGRAM), propocol=0)

    3. 創建tcp服務器:

      #! /usr/bin/env python
      # 創建tcp服務器。
      # ss = socket()創建服務器套接字
      # ss.bind()套接字與服務器綁定
      # ss.listen()監聽連接
      # inf_loop: 服務器無限循環
      #     cs = ss.accept()接受客戶端連接
      #     comm——loop:通行循環
      #         cs.revc()/cs.send()對話(接受/發送)
      #     cs.close()關閉客戶端套接字
      # ss.close()關閉服務器套接字(可選)
      from socket import *
      from time import ctime
      # 對bind()方法的標示,可以使用任何可用的地址,
      HOST = ''
      POST = 4747
      BUFSIZ = 1024
      ADDP = (HOST, POST)
      # 分派了TCP服務器套接字tcpSocket,將套接字綁定到服務器地址已及開啓TCP監聽器的調用。
      tcpSerSock = socket(AF_INET, SOCK_STREAM)
      # 將地址與監聽器綁定。
      tcpSerSock.bind(ADDP)
      # 設置並啓動tcp監聽器,參數傳入連接請求的最大次數。
      tcpSerSock.listen(5)
      # 監聽器無限循環
      while True:
         print( '等待連接!!....')
         # 被動接受tcp客戶端的連接,一直等待,直到連接到達。
         tcpCliSock, addr = tcpSerSock.accept()
         print('....連接 來自:', addr)
         # 通信循環
         while True:
             # 接受tcp 的消息
             data = tcpCliSock.recv(BUFSIZ)
             if not data:
                  break
             # 發送tcp消息。
             tcpCliSock.send('[%s] %s' %( bytes(ctime(),'utf-8'), data.decode('utf-8')))
         # 關閉客戶端套接字
         tcpCliSock.close()
      # 關閉服務器套件字
      tcpSerSock.close()
      

       

    4. 創建tcp客戶端:

      #! /usr/bin/env python
      # 創建TCP客戶端
      # cs = socket()創建客戶端套接字
      # cs.connect()嘗試連接服務器
      # comm_loop: 循環通信
      #     cs.send()/cs.recv()對話(發送/接收)
      # cs.close()關閉客戶端套接字
      
      from socket import *
      
      HOST = '127.0.0.1' # 本地迴環地址
      POST = 4747
      BUFSIZ = 1024
      ADDR = (HOST, POST)
      # 建立tcp套接字
      tcpCliSock = socket(AF_INET, SOCK_STREAM)
      # 主動發起tcp服務器連接。
      tcpCliSock.connect(ADDR)
      
      while True:
          # 輸入數據
          data = input('>')
          if not data:
              break
          # 發送tcp消息
          tcpCliSock.send(data.encode('utf-8'))
          #  接收tcp消息
          data = tcpCliSock.recv(BUFSIZ)
          if not data:
              print(data.decode('utf-8'))
      # 關閉tcp連接
      tcpCliSock.close()

       

    5. 執行tcp服務器可客戶端:

      等待連接!!....
      ....連接 來自: ('127.0.0.1', 51365)
      等待連接!!....

       

    6. 創建udp服務器:

      #UDP服務器
      # ss = socket() 創建服務器套接字
      # ss.bind() 綁定服務器套接字
      # int_loop:服務器無限循環
      #     cs = ss.recvfrom()\ss.sendto() 接受發送UDP消息
      # ss.colse() 關閉套接字
      
      from socket import *
      from time import ctime
      
      HOST = ''
      POST = 1111
      BUFSIZ = 1024
      ADDR = (HOST, POST)
      
      udpSerSock = socket(AF_INET, SOCK_DGRAM)
      udpSerSock.bind(ADDR)
      
      while True:
          print('等待連接')
          # 接受UDP消息
          data, addr = udpSerSock.recvfrom(BUFSIZ)
          # 發送UDP消息
          udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
          print('received from and returned to:',addr)
      udpSerSock.close()

       

    7. 創建udp客戶端:

      #!創建UDP客戶端,
      # cs = socket()創建客戶端套接字
      # comm_loop: 通行循環
      #   cs.sendto()\cs.recvfrom() #對話
      # cs.close() 關閉客戶端套接字。
      
      from  socket import  *
      from time import ctime
      
      HOST = 'localhost'
      POST = 1111
      BUFSIZ = 1024
      ADDR = (HOST, POST)
      
      udpSerSock = socket(AF_INET, SOCK_DGRAM)
      
      
      while True:
          data = input('>')
          if not data:
              break
          # 發送UDP消息
          udpSerSock.sendto(data.encode(), ADDR)
          #  接受UDP消息
          data, ADDR = udpSerSock.recvfrom(BUFSIZ)
          if not data:
              break
          print(data)
      udpSerSock.close()

       

    8. 執行udp服務器和客戶端:

    9.  

        嗯,感覺基礎的那些沒學好,直接看這本書有些喫力,而且Demo大都不能實現,Linux也用的不好,等吧基礎在學學,把linux學好了之後在回來學這個吧,感覺就不應該看,浪費了一些時間.還不如看些別的.嗯,生活加油  ^_^.   2019.9.7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章