1. 程式人生 > >python學習之路day05

python學習之路day05

本節大綱:

  1. 模組介紹
  2. time &datetime模組
  3. random
  4. os
  5. sys
  6. shutil
  7. json & picle
  8. shelve
  9. xml處理
  10. yaml處理
  11. configparser
  12. hashlib
  13. subprocess
  14. logging模組
  15. re正則表示式

1.模組

1.1定義:用來從邏輯上組織python程式碼(變數,函式,類,邏輯:實現一個功能),本質就是.py結尾的python檔案(檔名:test.py)

注:包的定語:本質就是一個目錄(必須帶一個_init_.py檔案)。用來從邏輯上組織模組。

1.2.匯入方法:

import module_test

import module_test,module_test1,module_test2

from module_test  import *(這個方法可忽略)

from module_test  import m1,m2,m3

from module_test import logger as  logger_alex

1.3impot本質(路徑搜尋和搜尋路徑)

匯入模組的本質就是把python檔案解釋一遍

import module_test---->imodule_test。py------>imodule_test.py的路徑---->sys.path(搜尋路徑)

匯入包的本質就是執行該包下的_init_.py檔案

1.4匯入優化

rom module_test  import m1

1.5模組的分類

a.標準庫

b.開源模組

c.自定義模組

標準庫:

2.time與datetime

4 import time 5 
7 # print(time.clock()) #返回處理器時間,3.3開始已廢棄 , 改成了time.process_time()測量處理器運算時間,不包括sleep時間,不穩定,mac上測不出來
8 # print(time.altzone) #返回與utc時間的時間差,以秒計算\
9 # print(time.asctime()) #返回時間格式"Fri Aug 19 11:14:16 2016",
10 # print(time.localtime()) #返回本地時間 的struct time物件格式
11 # print(time.gmtime(time.time()-800000)) #返回utc時間的struc時間物件格式
13 # print(time.asctime(time.localtime())) #返回時間格式"Fri Aug 19 11:14:16 2016",
14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
18 # 日期字串 轉成 時間戳
19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #將 日期字串 轉成 struct時間物件格式
20 # print(string_2_struct)
21 # #
22 # struct_2_stamp = time.mktime(string_2_struct) #將struct時間物件轉成時間戳
23 # print(struct_2_stamp)
27 #將時間戳轉為字串格式
28 # print(time.gmtime(time.time()-86640)) #將utc時間戳轉換成struct_time格式
29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #將utc struct_time格式轉成指定的字串格式

3.random模組

 

3.1隨機數 import random print random.random() print random.randint( 1 , 2 ) print random.randrange( 1 , 10 ) 3.2生成隨機碼 import random checkcode = '' for i in range ( 4 ):      current = random.randrange( 0 , 4 )      if current ! = i:          temp = chr (random.randint( 65 , 90 ))      else :          temp = random.randint( 0 , 9 )      checkcode + = str (temp) print checkcode 4.OS模組 os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑 os.chdir( "dirname" )  改變當前指令碼工作目錄;相當於shell下cd os.curdir  返回當前目錄: ( '.' ) os.pardir  獲取當前目錄的父目錄字串名:( '..' ) os.makedirs( 'dirname1/dirname2' )    可生成多層遞迴目錄 os.removedirs( 'dirname1' )    若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir( 'dirname' )    生成單級目錄;相當於shell中mkdir dirname os.rmdir( 'dirname' )    刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname os.listdir( 'dirname' )    列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印 os.remove()  刪除一個檔案 os.rename( "oldname" , "newname" )  重新命名檔案 / 目錄 os.stat( 'path/filename' )  獲取檔案 / 目錄資訊 os.sep    輸出作業系統特定的路徑分隔符,win下為 "\\",Linux下為" / " os.linesep    輸出當前平臺使用的行終止符,win下為 "\t\n" ,Linux下為 "\n" os.pathsep    輸出用於分割檔案路徑的字串 os.name    輸出字串指示當前使用平臺。win - > 'nt' ; Linux - > 'posix' os.system( "bash command" )  執行shell命令,直接顯示 os.environ  獲取系統環境變數 os.path.abspath(path)  返回path規範化的絕對路徑 os.path.split(path)  將path分割成目錄和檔名二元組返回 os.path.dirname(path)  返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path)  返回path最後的檔名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素 os.path.exists(path)  如果path存在,返回 True ;如果path不存在,返回 False os.path.isabs(path)  如果path是絕對路徑,返回 True os.path.isfile(path)  如果path是一個存在的檔案,返回 True 。否則返回 False os.path.isdir(path)  如果path是一個存在的目錄,則返回 True 。否則返回 False os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑之前的引數將被忽略 os.path.getatime(path)  返回path所指向的檔案或者目錄的最後存取時間 os.path.getmtime(path)  返回path所指向的檔案或者目錄的最後修改時間 5.sys模組 sys.argv           命令列引數 List ,第一個元素是程式本身路徑 sys.exit(n)        退出程式,正常退出時exit( 0 ) sys.version        獲取Python解釋程式的版本資訊 sys.maxint         最大的 Int sys.path           返回模組的搜尋路徑,初始化時使用PYTHONPATH環境變數的值 sys.platform       返回作業系統平臺名稱 sys.stdout.write( 'please:' ) val = sys.stdin.readline()[: - 1 ] 6.shutil 模組 直接參考 http://www.cnblogs.com/wupeiqi/articles/4963027.html  7.json & pickle 模組

用於序列化的兩個模組

  • json,用於字串 和 python資料型別間進行轉換
  • pickle,用於python特有的型別 和 python的資料型別間進行轉換

Json模組提供了四個功能:dumps、dump、loads、load

pickle模組提供了四個功能:dumps、dump、loads、load

8.xml處理模組

xml是實現不同語言或程式之間進行資料交換的協議,跟json差不多,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,大家只能選擇用xml呀,至今很多傳統公司如金融行業的很多系統的介面還主要是xml。

xml的格式如下,就是通過<>節點來區別資料結構的:

import xml.etree.ElementTree as ET   tree = ET.parse( "xmltest.xml" ) root = tree.getroot() print (root.tag)   #遍歷xml文件 for child in root:      print (child.tag, child.attrib)      for i in child:          print (i.tag,i.text)   #只遍歷year 節點 for node in root. iter ( 'year' ):      print (node.tag,node.text) 修改XML import xml.etree.ElementTree as ET   tree = ET.parse( "xmltest.xml" ) root = tree.getroot() #修改 for node in root. iter ( 'year' ):      new_year = int (node.text) + 1      node.text = str (new_year)      node. set ( "updated" , "yes" )   tree.write( "xmltest.xml" )   #刪除node for country in root.findall( 'country' ):     rank = int (country.find( 'rank' ).text)     if rank > 50 :       root.remove(country) tree.write( 'output.xml' )

9.hashlib模組  

用於加密相關的操作,3.x裡代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法

import hashlib   m = hashlib.md5() m.update(b "Hello" ) m.update(b "It's me" ) print (m.digest()) m.update(b "It's been a long time since last time we ..." )   print (m.digest()) #2進位制格式hash print ( len (m.hexdigest())) #16進位制格式hash ''' def digest(self, *args, **kwargs): # real signature unknown      """ Return the digest value as a string of binary data. """      pass   def hexdigest(self, *args, **kwargs): # real signature unknown      """ Return the digest value as a string of hexadecimal digits. """      pass   ''' import hashlib   # ######## md5 ########   hash = hashlib.md5() hash .update( 'admin' ) print ( hash .hexdigest()) # ######## sha1 ######## hash = hashlib.sha1() hash .update( 'admin' ) print ( hash .hexdigest()) # ######## sha256 ######## hash = hashlib.sha256() hash .update( 'admin' ) print ( hash .hexdigest())   # ######## sha384 ######## hash = hashlib.sha384() hash .update( 'admin' ) print ( hash .hexdigest()) # ######## sha512 ######## hash = hashlib.sha512() hash .update( 'admin' ) print ( hash .hexdigest()) 注:更多關於md5,sha1,sha256等介紹的文章看這裡https://www.tbs-certificates.co.uk/FAQ/en/sha256.html  10.re模組 '.'     預設匹配除\n之外的任意一個字元,若指定flag DOTALL,則匹配任意字元,包括換行 '^'     匹配字元開頭,若指定flags MULTILINE,這種也可以匹配上(r "^a" , "\nabc\neee" ,flags = re.MULTILINE) '$'     匹配字元結尾,或e.search( "foo$" , "bfoo\nsdfsf" ,flags = re.MULTILINE).group()也可以 '*'     匹配 * 號前的字元 0 次或多次,re.findall( "ab*" , "cabb3abcbbac" )  結果為[ 'abb' , 'ab' , 'a' ] '+'     匹配前一個字元 1 次或多次,re.findall( "ab+" , "ab+cd+abb+bba" ) 結果[ 'ab' , 'abb' ] '?'     匹配前一個字元 1 次或 0 '{m}'   匹配前一個字元m次 '{n,m}' 匹配前一個字元n到m次,re.findall( "ab{1,3}" , "abb abc abbcbbb" ) 結果 'abb' , 'ab' , 'abb' ] '|'     匹配|左或|右的字元,re.search( "abc|ABC" , "ABCBabcCD" ).group() 結果 'ABC' '(...)' 分組匹配,re.search( "(abc){2}a(123|456)c" , "abcabca456c" ).group() 結果 abcabca456c     '\A'    只從字元開頭匹配,re.search( "\Aabc" , "alexabc" ) 是匹配不到的 '\Z'    匹配字元結尾,同$ '\d'    匹配數字 0 - 9 '\D'    匹配非數字 '\w'    匹配[A - Za - z0 - 9 ] '\W'    匹配非[A - Za - z0 - 9 ] 's'     匹配空白字元、\t、\n、\r , re.search( "\s+" , "ab\tc1\n3" ).group() 結果 '\t'   '(?P<name>...)' 分組匹配 re.search( "(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})" , "371481199306143242" ).groupdict( "city" ) 結果{ 'province' : '3714' , 'city' : '81' , 'birthday' : '1993' }   最常用的匹配方法 re.match 從頭開始匹配 re.search 匹配包含 re.findall 把所有匹配到的字元放到以列表中的元素返回 re.splitall 以匹配到的字元當做列表分隔符 re.sub      匹配字元並替換 僅需輕輕知道的幾個匹配模式 re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同) M(MULTILINE): 多行模式,改變 '^' '$' 的行為(參見上圖) S(DOTALL): 點任意匹配模式,改變 '.' 的行為   本節課作業

開發一個簡單的python計算器

  1. 實現加減乘除及拓號優先順序解析
  2. 使用者輸入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等類似公式後,必須自己解析裡面的(),+,-,*,/符號和公式(不能呼叫eval等類似功能偷懶實現),運算後得出結果,結果必須與真實的計算器所得出的結果一致