Python基礎-week05 Python經常使用模塊的使用

 

 

一.模塊介紹

  模塊,用一砣代碼實現了某個功能的代碼集合。 php

  相似於函數式編程和麪向過程編程,函數式編程則完成一個功能,其餘代碼用來調用便可,提供了代碼的重用性和代碼間的耦合。而對於一個複雜的功能來,可能須要多個函數才能完成(函數又能夠在不一樣的.py文件中),n個 .py 文件組成的代碼集合就稱爲模塊。html

  1.定義java

    模塊:用來從邏輯上組織python代碼(變量,函數,類,邏輯),本質就是.py結尾的python文件名,用途就是實現一個功能。node

    例如:文件名爲test.py,對應的模塊就是testpython

  2.導入方法
    import module_name1
    import module_name2,module_name3 #導入多個模塊
    from moudule_name import * #導入module_name中的全部函數和變量,可能會跟本地的函數重名。

    from module_name import logger() as logger2 #與本地的logger()函數重名,進行重命名!

    from和import的區別?
      from調用函數能夠直接使用,不用加模塊名.xx 來調用。
      import 調用須要用模塊名.xxx來調用。
mysql

  3.import本質(路徑搜索和搜索路徑)
    導入模塊的本質就是把python文件解釋一遍:import moudule_alex
    (至關於module_alex=all_code 把全部的代碼)
    import module_name --->module_name.py ---->module_name.py的路徑----》sys.path

    from test import m1 至關於m1='code'就能夠直接使用和讀取m1的值!


  4.導入優化
    #優化前!
    import module_testlinux

    #導入優化後爲,至關於把module_test的sayhello()函數拿到當前的文件中,不須要一遍遍的查找解釋!git


    from module_test import sayhello
    #也能夠加上 as 起個別名防止跟當前文件中的函數名衝突!es6

 5.模塊的分類
  a:標準庫:sys,os 等
    time和datetime
    strftime('格式',struct_time)---->'格式化的字符串'
    strptime('格式化的字符串','格式')--->struct_time(時間元祖)


  b:開源模塊(第三方模塊)
    yum install gcc等這類開源模塊,也能夠wget 下載源碼包手動安裝。
  c.自定義模塊
    本身定義的python模塊,提供給其餘的py文件使用。正則表達式

 

  更詳細的模塊說明請參考武老師:http://www.cnblogs.com/wupeiqi/articles/4963027.html 

 

 6.模塊的表現形式

  1 使用python編寫的.py文件

  2 已被編譯爲共享庫或DLL的C或C++擴展

  3 把一系列模塊組織到一塊兒的文件夾(注:文件夾下有一個__init__.py文件,該文件夾稱之爲包)

  4 使用C編寫並連接到python解釋器的內置模塊

  

二.time & datetime 模塊

  1.time & datetime 方法實例

 1 import time
 2 
 3 
 4 #1.時間戳,經過gmtime轉換成元祖
 5 x=time.time() #這個取出來的時間爲分界點的時間,若是是中國要+8小時東八區,locatime能夠直接取時間。
 6 gmt=time.gmtime(x) #x不寫默認爲localtime本地時間
 7 print (gmt.tm_year,'',gmt.tm_mon,'',gmt.tm_mday,'')
 8 
 9 
10 
11 
12 #2.格式化的時間字符串,gmt是將秒轉換成元祖的格式。
13 #元祖轉換成字符串
14 strtime=time.strftime("%Y-%m-%d %H:%M:%S",gmt)
15 strtime2=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
16 print (strtime)
17 print (strtime2)
18 
19 #字符串轉換成元祖,與strftime正好相反,格式能夠隨意排版,可是要與%H等參數對應。
20 print(time.strptime("2018-03-28 02:14:15","%Y-%m-%d %H:%M:%S"))
21 print(time.strptime("02:14:15 2018-03-12","%H:%M:%S %Y-%m-%d"))
22 sruct_time1=time.strptime("02:14:15 2018-03-12","%H:%M:%S %Y-%m-%d")
23 
24 #將元祖轉換成字符串,若是不傳參默認當前時間
25 print (time.asctime(sruct_time1))
26 print (time.asctime())
27 #(Wed Mar 28 17:48:04 2018)
28 
29 #,若是不傳參默認當前時間
30 print (time.ctime())
31 #(Wed Mar 28 17:48:04 2018)
32 
33 
34 #3.元祖,共九個元素
35 print(time.localtime()) #至關於 x=time.time() gmt=time.gmtime(x)
36 
37 #將秒轉換成元祖,並取出其中指定的天
38 lt=time.localtime(123213123)
39 print ("in 1973 year's %d day!" %lt.tm_yday )
40 
41 #將元祖轉換成秒
42 print(time.mktime(lt))
time實例

 

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import datetime
 3 #1.取當前時間
 4 print (datetime.datetime.now())
 5 
 6 #2.當前時間+3天
 7 print (datetime.datetime.now()+datetime.timedelta(3))
 8 
 9 #3.當前時間 -3天
10 print (datetime.datetime.now()+datetime.timedelta(-3))
11 
12 #4.當前時間 +3小時
13 print (datetime.datetime.now()+datetime.timedelta(hours=3))
14 
15 #4.當前時間 -30分鐘
16 print (datetime.datetime.now()+datetime.timedelta(minutes=-30))
datetime實例

  2.time & datetime圖,練習完實例後多思考如下圖

 

 

 

 

 

 

三.random模塊

  1.random經常使用方法實例

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import random
 3 
 4 '''random的實際應用:'''
 5 
 6 #1.隨機整數,randint 包括5
 7 print (random.randint(1,5))
 8 
 9 #2.隨機選取0-100的偶數,不包括101
10 print (random.randrange(0,101,2))
11 
12 #3.隨機浮點數1個,uniform範圍不包括2;random(),默認1之內的
13 print (random.random())
14 print(random.uniform(1,2))
15 
16 #4.隨機字符串
17 print (random.choice('abcd'))
18 #從多個字符串中選取 多個字符串
19 print (random.sample(['abc','jame','tomcat'],2))
20 
21 
22 #5.洗牌
23 item=[1,2,3,4,5]
24 print ('before:',item)
25 random.shuffle(item)
26 print ('after:',item)
random經常使用實例

  2.random的隨機數應用

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import random
 3 import string
 4 
 5 #打印4位數字(字母+數字隨意)的驗證碼
 6 checkcode=''
 7 for i in range(5):
 8     current=random.randrange(0,5)
 9     #字母
10     if current==i:
11         tmp=chr(random.randint(65,90)) #chr將數字轉換成ASCII碼對應的字母!!
12     #數字
13     else:
14         tmp=random.randint(0,9)
15 
16     checkcode+=str(tmp)
17 
18 print (checkcode)
隨機數

 

 

四.os模塊(系統經常使用)

  1.os模塊經常使用方法練習

  1 #Author:http://www.cnblogs.com/Jame-mei
  2 import  os
  3 import time
  4 
  5 #1.getcwd(),獲取該腳本的目錄
  6 #os.chdir("E:\pythonwork\s14\os")
  7 print (os.getcwd())
  8 
  9 #2.chdir,至關於cd,再os.getcwd()來獲取當前的目錄才能看出效果
 10 os.chdir("E:\pythonwork\s14")
 11 print (os.getcwd())
 12 
 13 #3.curdir
 14 print (os.curdir)
 15 
 16 #4.pardir 獲取當前目錄父目錄的字符串名:..
 17 print (os.pardir)
 18 
 19 #5.mkdirs,可生成多個遞歸目錄,在當前目錄下新建了os/test1/test2目錄
 20 #os.makedirs('os/test1/test2')
 21 
 22 #6.removedir,要求目錄不爲空的狀況下
 23 #os.removedirs(r"E:\pythonwork\s14\day05\os\os_test")
 24 
 25 #7.建立和刪除目錄
 26 #os.mkdir(r"E:\pythonwork\s14\day05\os\test_os2")
 27 #生成單級目錄;至關於shell中mkdir dirname
 28 
 29 #os.rmdir(r"E:\pythonwork\s14\day05\os\test_os2")
 30 #刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname
 31 
 32 
 33 #8.listdir 列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印
 34 print(os.listdir('E:\pythonwork\s14\os'))
 35 
 36 
 37 #9.刪除一個文件
 38 #os.remove(r'E:\pythonwork\s14\day05\os\remove_test.py')
 39 
 40 #10.rename('oldname','newname') 重命名文件或者目錄,其中windows裏面的路徑要加r,或者\來進行轉義!
 41 #os.rename(r'E:\pythonwork\s14\day05\os\rename_test.py',r'E:\pythonwork\s14\day05\os\rename_test2.py')
 42 
 43 
 44 
 45 #11.stat(path/filename) 獲取文件、目錄信息
 46 print (os.stat(r'E:\pythonwork\s14\day05\os\test1.py'))
 47 
 48 #12.sep 輸出操做系統特定的路徑分隔符,能夠進行跨平臺,換個linux就變了/了
 49 print (os.sep)
 50 #.linsep 輸出當前平安體使用的行終止符
 51 print (os.linesep)
 52 #.pathsep 輸出用於分割文件路徑的字符串
 53 print(os.pathsep)
 54 
 55 
 56 #13.name 輸出字符串指示當前使用平臺
 57 print (os.name)
 58 
 59 #14.system()運行shell命令,直接顯示
 60 print (os.system("ls -l"))
 61 
 62 #15.environ 獲取系統環境變量
 63 print (os.environ)
 64 
 65 #16.os.path大類!
 66 
 67 #os.path.abspath() 返回path規範化的絕對路徑,
 68 print (os.path.abspath('test1.py'))
 69 
 70 #os.path.split(path) 將path分割成目錄和文件名二元組返回
 71 print (os.path.split('E:\pythonwork\s14\day05\os\test1.py'))
 72 #output:('E:\\pythonwork\\s14\\day05', 'os\test1.py') 這樣一個元祖。
 73 
 74 
 75 #返回path的目錄。其實就是os.path.split(path)的第一個元素
 76 print (os.path.dirname('E:\pythonwork\s14\day05\os\test1.py'))
 77 
 78 
 79 # os.path.basename(path)  返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
 80 print (os.path.basename('E:\pythonwork\s14\day05\os\test1.py'))
 81 
 82 # os.path.exists(path)  若是path存在,返回True;若是path不存在,返回False
 83 print (os.path.exists(r'E:\pythonwork\s14\day05\os\test1.py'))
 84 
 85 # os.path.isabs(path)  若是path是絕對路徑,返回True
 86 print (os.path.exists(r'E:\pythonwork\s14\day05\os\test1.py'))
 87 
 88 # os.path.isfile(path)  若是path是一個存在的文件,返回True。不然返回False
 89 print (os.path.isfile(r'E:\pythonwork\s14\day05\os\test1.py'))
 90 
 91 # os.path.isdir(path)  若是path是一個存在的目錄,則返回True。不然返回False
 92 print (os.path.isdir(r'E:\pythonwork\s14\day05\os'))
 93 
 94 # os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略
 95 print (os.path.join(r'E:\pythonwork\s14',r'day05',r'os',r'test1.py'))
 96 #output:E:\pythonwork\s14\day05\os\test1.py
 97 
 98 # os.path.getatime(path)  返回path所指向的文件或者目錄的最後存取時間
 99 filetime=os.path.getatime(r"E:\pythonwork\s14\day05\os\rename_test2.py") #返回的秒數
100 print (time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(filetime))) #先轉換成元祖,再轉換成指定格式的時間。
101 
102 # os.path.getmtime(path)  返回path所指向的文件或者目錄的最後修改時間
103 motime=os.path.getmtime(r"E:\pythonwork\s14\day05\os\rename_test2.py")
104 print (time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(motime)))
os模塊經常使用的方法練習

  2.更多參考官方文檔

  https://docs.python.org/2/library/os.html?highlight=os#module-os

 

 

五.sys模塊(系統經常使用)

  1.sys模塊經常使用方法練習

    

 1 #1.argv  命令行參數List,第一個元素是程序自己路徑
 2 print (sys.argv)
 3 #output:['E:/pythonwork/s14/day05/sys/sys_test1.py']
 4 
 5 
 6 #2.exit(n)
 7 #sys.exit(0)
 8 
 9 #3.version
10 print (sys.version)
11 #output: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
12 
13 #4.maxint,python3已經找不到該方法了
14 
15 #5.path
16 print (sys.path)
17 
18 #6.sys.platform,輸出的是win32的操做系統的信息
19 print (sys.platform)
20 
21 #7.stdout,標準輸出
22 sys.stdout.write('please:')
23 val = sys.stdin.readline()[:-1]
24 print (val)
sys常見方法

 

  2.更多參考官方文檔

    https://docs.python.org/2/library/sys.html?highlight=sys#module-sys

 

六.shutil模塊

  高級的 文件、文件夾、壓縮包 處理模塊。

  1.拷貝(src爲源文件,dst爲目標文件)

    shutil.copy(src, dst)
    拷貝文件和權限

 

    shutil.copy2(src, dst)
    拷貝文件和狀態信息

    

    shutil.copyfile(src, dst)

    拷貝文件

    

    shutil.copyfileobj(fsrc, fdst[, length])
    將文件內容拷貝到另外一個文件中,能夠部份內容

1 f1=open("本節筆記",encoding='utf-8')
2 f2=open("筆記2",'w',encoding='utf-8')
3 #shutil.copyfileobj(f1,f2)
copyfileobj(file1,file2)

 

    shutil.copymode(src, dst)
    僅拷貝權限。內容、組、用戶均不變

 

    shutil.copystat(src, dst)
    拷貝狀態的信息,包括:mode bits, atime, mtime, flags

 

    shutil.ignore_patterns(*patterns)
    shutil.copytree(src, dst, symlinks=False, ignore=None)
    遞歸的去拷貝文件(經常使用)

1 遞歸的去拷貝文件,這個經常使用!
2 #shutil.copytree(r"E:/pythonwork/s14/day05/shutil",r"E:/pythonwork/s14/day05/shutil/newshutil")
copytree經常使用

 

 

  2.刪除

    shutil.rmtree(path[, ignore_errors[, onerror]])
    遞歸的去刪除文件(經常使用)

 

1 #遞歸的去刪除文件
2 #shutil.rmtree(r"E:/pythonwork/s14/day05/shutil/newshutil")
rmtree對刪除,經常使用

 

  

  3.移動

    shutil.move(src, dst)
    遞歸的去移動文件

 

  4.壓縮和解壓

    shutil.make_archive(base_name, format,...)

    建立壓縮包並返回文件路徑,例如:zip、tar

    • base_name: 壓縮包的文件名,也能夠是壓縮包的路徑。只是文件名時,則保存至當前目錄,不然保存至指定路徑,
      如:www                        =>保存至當前路徑
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」
    • root_dir: 要壓縮的文件夾路徑(默認當前目錄)
    • owner: 用戶,默認當前用戶
    • group: 組,默認當前組
    • logger: 用於記錄日誌,一般是logging.Logger對象

     

      實例:shutil.make_archive():

1 #建立壓縮包並返回文件路徑,例如:zip、tar,會把shutil目錄下的全部壓縮備份到當前目錄的backup_py.zip,最好壓縮到其餘地方避免死循環。
2 ret = shutil.make_archive(r"D:\pytest\backup_py", 'zip', root_dir='E:/pythonwork/s14/day05/shutil')
make_archive(base_name,format...)

     4.1.zipfile 壓縮解壓

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import zipfile
 3 
 4 # 壓縮
 5 z = zipfile.ZipFile('ziptest.zip', 'w')
 6 z.write('test1.py') #將要壓縮的文件寫入!!
 7 z.write('本節筆記')
 8 z.close()
 9 
10 # 解壓
11 z = zipfile.ZipFile('ziptest.zip', 'r')
12 z.extractall(path="ziptest") #將ziptest.zip解壓到當前文件夾下,娶一個名字叫ziptest
13 z.close()
zipfile壓縮解壓

 

     4.2.tarfile壓縮解壓

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import tarfile
 3 
 4 #1.壓縮
 5 tf=tarfile.open('tarfile.tar','w')
 6 tf.add(r'E:/pythonwork/s14/day05/shutil/ziptest.zip','ziptest.zip')
 7 tf.close()
 8 
 9 
10 #2.解壓
11 zf=tarfile.open('tarfile.tar','r')
12 zf.extractall(r"E:/pythonwork/s14/day05/shutil/tarfile") #解壓成這個目錄下,名字叫tarfile的文件夾!
13 zf.close()
tarfile.open(name,model=r/w)

 

  

七.json & pickle(文件保存及網絡傳輸經常使用)

  用於序列化的兩個模塊

  • json,用於字符串 和 python數據類型間進行轉換,解決了不通語言之間的通訊例如java/php等。
  • pickle,用於python特有的類型 和 python的數據類型間進行轉換,解決了python語言內部的通訊。

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

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

  

  

  更多詳情見:python基礎-week04的json&pickle章節內容!

 

八.shelve

  shelve模塊是一個簡單的k,v將內存數據經過文件持久化的模塊,能夠持久化任何pickle可支持的python數據格式。

  

  shelve存入讀取實例:

  

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import shelve
 3 import datetime
 4 
 5 d = shelve.open('shelve_test')  # 打開一個文件
 6 t=datetime.datetime.now()
 7 
 8 # class Test(object):
 9 #     def __init__(self, n):
10 #         self.n = n
11 
12 info={'age':24,'job':'it'}
13 name = ["alex", "rain", "test"]
14 
15 #1.寫入
16 d["names"] = name  # 持久化列表
17 d["dicts"] =info  # 持久化字典
18 d['tz']=t         #持久化時間類型
19 
20 
21 #2.讀出來
22 print(d.get('names'))
23 print(d.get('dicts'))
24 print (d.get('tz'))
shelve.open(...)

 

九.xml處理(1-2)

  1.xml簡介和格式

  xml是實現不一樣語言或程序之間進行數據交換的協議,跟json差很少,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,你們只能選擇用xml呀,至今不少傳統公司如金融行業的不少系統的接口還主要是xml。

xml的格式以下,就是經過<>節點來區別數據結構的:

  

 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>
xml格式範文:

  xml協議在各個語言裏的都 是支持的,在python中能夠用如下模塊操做xml :

  1.遍歷xml的內容和子節點標籤

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import xml.etree.ElementTree as xeet
 3 
 4 tree=xeet.parse('test_xml.xml')
 5 root=tree.getroot()
 6 
 7 print (root)
 8 print (root.tag,root.text)
 9 
10 
11 
12 
13 #1.遍歷xml文件 ,tag標籤,attrib屬性,text標籤的值
14 for child in root:
15     print (child.tag,child.attrib)
16     for i in child:
17         print (i.tag,i.attrib,i.text)
18     print("=============================================================>>>")
19 
20 
21 
22 #2.只遍歷 rank子節點標籤的屬性和內容 
23 #只遍歷year 節點
24 for node in root.iter('rank'):
25     print(node.tag,node.text,node.attrib)
遍歷xml

  2.刪除、修改xml

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 
 3 import xml.etree.ElementTree as xee
 4 
 5 
 6 tree=xee.parse("test_xml.xml")
 7 root=tree.getroot()
 8 
 9 1.批量修改 rank標籤中的值
10 for node in root.iter('rank'):
11      new_rank=int(node.text)+10
12      node.text=str(new_rank)
13      node.set('update','yes')
14 
15 tree.write('test_xml.xml')
16 
17 
18 
19 
20 #2.刪除
21 for country in root.findall('country'):
22     rank=int(country.find('rank').text)
23     if rank>50:
24         root.remove(country)
25 
26 tree.write('output.xml') #將刪除後的文本保存到output.xml中,這樣能夠保證源文件不會誤操做沒法恢復的狀況。
View Code

   3.本身建立生成一個xml文件

 1 #Author:http://www.cnblogs.com/Jame-mei
 2 import xml.etree.ElementTree as ET
 3 
 4 new_xml = ET.Element("namelist")
 5 
 6 name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
 7 age = ET.SubElement(name, "age", attrib={"checked": "no"})
 8 age.text = '33'
 9 sex = ET.SubElement(name, "sex")
10 sex.text="男"
11 
12 
13 name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
14 age = ET.SubElement(name2, "age")
15 age.text = '19'
16 
17 et = ET.ElementTree(new_xml)  # 生成文檔對象
18 et.write("test.xml", encoding="utf-8", xml_declaration=True)
19 
20 ET.dump(new_xml)  # 打印生成的格式
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 輸出:
32 
33 <?xml version='1.0' encoding='utf-8'?>
34 <namelist>
35     <name enrolled="yes">
36         <age checked="no">33</age>
37         <sex></sex>
38     </name>
39     <name enrolled="no">
40         <age>19</age>
41     </name>
42 </namelist>
建立xml文件

  

    

十.yaml處理

  Python也能夠很容易的處理ymal文檔格式,只不過須要安裝一個模塊,參考文檔:http://pyyaml.org/wiki/PyYAMLDocumentation 

  開源的Ansible,Saltstack的配置文件都是用yaml寫的。

 

十一.configparser

  用於生成和修改常見配置文檔,當前模塊的名稱在 python 3.x 版本中變動爲 configparser。

  來看一個好多軟件的常見文檔格式以下:

  [DEFAULT]

  ServerAliveInterval  =  45
  Compression  =  yes
  CompressionLevel  =  9
  ForwardX11  =  yes
 
  [bitbucket.org]
  User  =  hg
 
  [topsecret.server.com]
  Port  =  50022
  ForwardX11  =  no
 
  實例:本身用Python的configparser()來生成相似上面的配置文件:
  #1.寫入
  
 1 #Author http://www.cnblogs.com/Jame-mei
 2 import configparser  #python2.x ConfigParser 大寫
 3 
 4 config = configparser.ConfigParser()
 5 
 6 config["DEFAULT"] = {'ServerAliveInterval': '45',
 7                      'Compression': 'yes',
 8                      'CompressionLevel': '9'}
 9 config['DEFAULT']['ForwardX11'] = 'yes'
10 
11 
12 config['bitbucket.org'] = {}
13 config['bitbucket.org']['User'] = 'hg'
14 
15 config['topsecret.server.com'] = {}
16 topsecret = config['topsecret.server.com'] 
17 topsecret['Host Port'] = '50022'  # mutates the parser
18 topsecret['ForwardX11'] = 'no'    #same here
19 
20 
21 
22 #最後寫入!
23 with open('example.ini', 'w') as configfile:
24     config.write(configfile)
25 
26 
27 ================================================================================
28 輸出以下:
29 [DEFAULT]
30 serveraliveinterval = 45
31 compression = yes
32 compressionlevel = 9
33 forwardx11 = yes
34 
35 [bitbucket.org]
36 user = hg
37 
38 [topsecret.server.com]
39 host port = 50022
40 forwardx11 = no
configparser生成配置文件

  #2.讀出

 

 1 [DEFAULT]
 2 serveraliveinterval = 45
 3 compression = yes
 4 compressionlevel = 9
 5 forwardx11 = yes
 6 
 7 [bitbucket.org]
 8 user = hg
 9 
10 [topsecret.server.com]
11 host port = 50022
12 forwardx11 = no
配置源文件
 1 #Author http://www.cnblogs.com/Jame-mei
 2 import configparser
 3 
 4 config=configparser.ConfigParser()
 5 
 6 
 7 config.read('example.ini')
 8 print(config.sections())  #打印出除了默認標籤,之外的標籤!!
 9 print(config.defaults())
10 '''
11 輸出:
12 ['bitbucket.org', 'topsecret.server.com']
13 OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
14 '''
15 
16 print (config['bitbucket.org']['User'])
17 print (config['DEFAULT']['Compression'])
18 '''
19 輸出:
20 hg
21 yes
22 
23 '''
24 
25 topsecret = config['topsecret.server.com']
26 print (topsecret['ForwardX11'])
27 print (topsecret['host port'])
28 '''
29 輸出:
30 no
31 50022
32 '''
33 
34 print ('遍歷configparaser-default默認標籤的屬性名==============================>>>>>>>>>>>>>>>>>>>>>>')
35 for key in config['DEFAULT']:
36     print(key)
37 '''
38 輸出:
39 serveraliveinterval
40 compression
41 compressionlevel
42 forwardx11
43 '''
44 
45 
46 print('遍歷configparaser----bitbucket.org標籤的屬性名+default默認屬性名==============================>>>>>>>>>>>>>>>>>>>>>>')
47 for key in config['bitbucket.org']:
48     print (key)
49 '''
50 遍歷:
51 user
52 serveraliveinterval
53 compression
54 compressionlevel
55 forwardx11
56 '''
57 
58 
59 print('遍歷configparaser----topsecret.server.com標籤的屬性名+default默認屬性名==============================>>>>>>>>>>>>>>>>>>>>>>')
60 for key in config['topsecret.server.com']:
61     print (key)
62 '''
63 輸出:
64 host port
65 forwardx11
66 serveraliveinterval
67 compression
68 compressionlevel
69 
70 '''
71 
72 
73 #總結,遍歷default就是隻遍歷default默認屬性的名
74 # 遍歷其餘標籤的屬性名,也會遍歷出default的屬性名!
讀取配置源文件的代碼!

 

  #3.configparser增刪改查語法

  

 1 [section1]
 2 k1 = v1
 3 k2:v2
 4   
 5 [section2]
 6 k1 = v1
 7  
 8 import ConfigParser
 9   
10 config = ConfigParser.ConfigParser()
11 config.read('i.cfg')
12   
13 # ########## 讀 ##########
14 #secs = config.sections()
15 #print secs
16 #options = config.options('group2')
17 #print options
18   
19 #item_list = config.items('group2')
20 #print item_list
21   
22 #val = config.get('group1','key')
23 #val = config.getint('group1','key')
24   
25 # ########## 改寫 ##########
26 #sec = config.remove_section('group1')
27 #config.write(open('i.cfg', "w"))
28   
29 #sec = config.has_section('wupeiqi')
30 #sec = config.add_section('wupeiqi')
31 #config.write(open('i.cfg', "w"))
32   
33   
34 #config.set('group2','k1',11111)
35 #config.write(open('i.cfg', "w"))
36   
37 #config.remove_option('group2','age')
38 #config.write(open('i.cfg', "w"))
增刪改查請多練習

 

 

十二.hashlib(加密經常使用)

  用於加密相關的操做,3.x裏代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法:

  

 1 import hashlib
 2  
 3 m = hashlib.md5()
 4 m.update(b"Hello")
 5 m.update(b"It's me")
 6 print(m.digest())
 7 m.update(b"It's been a long time since last time we ...")
 8  
 9 print(m.digest()) #2進制格式hash
10 print(len(m.hexdigest())) #16進制格式hash
11 '''
12 def digest(self, *args, **kwargs): # real signature unknown
13     """ Return the digest value as a string of binary data. """
14     pass
15  
16 def hexdigest(self, *args, **kwargs): # real signature unknown
17     """ Return the digest value as a string of hexadecimal digits. """
18     pass
19  
20 '''
21 import hashlib
22  
23 # ######## md5 ########
24  
25 hash = hashlib.md5()
26 hash.update('admin')
27 print(hash.hexdigest())
28  
29 # ######## sha1 ########
30  
31 hash = hashlib.sha1()
32 hash.update('admin')
33 print(hash.hexdigest())
34  
35 # ######## sha256 ########
36  
37 hash = hashlib.sha256()
38 hash.update('admin')
39 print(hash.hexdigest())
40  
41  
42 # ######## sha384 ########
43  
44 hash = hashlib.sha384()
45 hash.update('admin')
46 print(hash.hexdigest())
47  
48 # ######## sha512 ########
49  
50 hash = hashlib.sha512()
51 hash.update('admin')
52 print(hash.hexdigest())
加密練習

 

  還不夠吊?python 還有一個 hmac 模塊,它內部對咱們建立 key 和 內容 再進行處理而後再加密散列消息鑑別碼,簡稱HMAC,是一種基於消息鑑別碼MAC(Message Authentication Code)的鑑別機制。使用HMAC時,消息通信的雙方,經過驗證消息中加入的鑑別密鑰K來鑑別消息的真僞;

  通常用於網絡通訊中消息加密,前提是雙方先要約定好key,就像接頭暗號同樣,而後消息發送把用key把消息加密,接收方用key + 消息明文再加密,拿加密後的值 跟 發送者的相對比是否相等,這樣就能驗證消息的真實性,及發送者的合法性了。

 

 

  

1 #Author http://www.cnblogs.com/Jame-mei
2 import hmac
3 
4 h=hmac.new('天王蓋地虎'.encode(encoding='utf-8'),'小雞燉蘑菇'.encode(encoding='utf-8'))
5 
6 print (h.digest())
7 print (h.hexdigest())
hmac

 

 

更多關於md5,sha1,sha256等介紹的文章看這裏https://www.tbs-certificates.co.uk/FAQ/en/sha256.html 

十三.subprocess

    

import  subprocess

'''
sh-3.2# ls /Users/egon/Desktop |grep txt$
mysql.txt
tt.txt
事物.txt
'''

res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
                 stdout=subprocess.PIPE)

print(res.stdout.read().decode('utf-8'))


#等同於上面,可是上面的優點在於,一個數據流能夠和另一個數據流交互,能夠經過爬蟲獲得結果真後交給grep
res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
print(res1.stdout.read().decode('utf-8'))


#windows下:
# dir | findstr 'test*'
# dir | findstr 'txt$'
import subprocess
res1=subprocess.Popen(r'dir C:\Users\Administrator\PycharmProjects\test\函數備課',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
                 stdout=subprocess.PIPE)

print(res.stdout.read().decode('gbk')) #subprocess使用當前系統默認編碼,獲得結果爲bytes類型,在windows下須要用gbk解碼
subprocess練習

 

 

 

十四.logging模塊(經常使用)

  不少程序都有記錄日誌的需求,而且日誌中包含的信息即有正常的程序訪問日誌,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日誌接口,你能夠經過它存儲各類格式的日誌,logging的日誌能夠分爲 debug()info()warning()error() and critical() 5個級別,下面咱們看一下怎麼用。

  最簡單用法:

1
2
3
4
5
6
7
8
import  logging
 
logging.warning( "user [alex] attempted wrong password more than 3 times" )
logging.critical( "server is down" )
 
#輸出
WARNING:root:user [alex] attempted wrong password more than  3  times
CRITICAL:root:server  is  down

待續.... 

 

十五.re正則(對於爬蟲重要)

  經常使用正則表達式:

  

 1 '.'     默認匹配除\n以外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行
 2 '^'     匹配字符開頭,若指定flags MULTILINE,這種也能夠匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
 3 '$'     匹配字符結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也能夠
 4 '*'     匹配*號前的字符0次或屢次,re.findall("ab*","cabb3abcbbac")  結果爲['abb', 'ab', 'a']
 5 '+'     匹配前一個字符1次或屢次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb']
 6 '?'     匹配前一個字符1次或0次
 7 '{m}'   匹配前一個字符m次
 8 '{n,m}' 匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb']
 9 '|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC'
10 '(...)' 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c
11  
12  
13 '\A'    只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的
14 '\Z'    匹配字符結尾,同$
15 '\d'    匹配數字0-9
16 '\D'    匹配非數字
17 '\w'    匹配[A-Za-z0-9]
18 '\W'    匹配非[A-Za-z0-9]
19 's'     匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t'
20  
21 '(?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'}
經常使用

 

 1 #Author http://www.cnblogs.com/Jame-mei
 2 import re
 3 
 4 #match  .+以任意多個字符開頭,\d數字結尾
 5 res1=re.match("^.+\d", "cai123yuanhua")
 6 print (res1.group())
 7 #cai123
 8 
 9 #rearch {3}每次只匹配最多3個數字
10 res2=re.search("[0-9]{3}","aa123x2a34567aa")
11 print (res2.group())
12 #123
13 
14 re4=re.search("ABC|abc","abcABCCD").group()
15 print (re4)
16 #'abc',先匹配ABC沒有,又開始匹配abc
17 
18 res6=re.search("(abc){2}","alexabcabcabcbad")
19 print (res6.group())
20 #abcabc
21 
22 res7=re.search("(abc){2}a(123|456)c", "abcabca456c").group()
23 print ('res7:',res7)
24 #res7: abcabca456c
25 
26 res8=re.search(".*\D","alexabcabcabcbad.,&").group()
27 print (res8)
28 #alexabcabcabcbad.,& ,匹配非數字的全部
29 
30 res9=re.search("\D+","alexabcabcabcbad.,&").group()
31 print (res9)
32 #alexabcabcabcbad.,&
33 
34 
35 res10=re.search("\w+","AaBbCc13579&?!").group()
36 print (res10)
37 #AaBbCc13579
38 
39 res11=re.search("(?P<province>[0-9]{3})(?P<city>[0-9]{3})(?P<birthday>[0-9]{8})","371481199306143242").groupdict()
40 print (res11)
41 #{'province': '371', 'city': '481', 'birthday': '19930614'}
42 
43 
44 #findall {1,3} 最多每次最多隻能匹配到3個數字
45 print(re.findall("[0-9]{1,3}","aa1x2a34545aa"))
46 #output
47 #['1', '2', '345', '45']
48 
49 
50 res5=re.findall("ABC|abc","abABCCabcD")
51 print (res5)
52 #['ABC', 'abc']
53 
54 
55 
56 #re.slip
57 s1=re.split("[0-9]","abc1de2f9gh10")
58 #['abc', 'de', 'f', 'gh', '', '']
59 
60 
61 #rs.sub
62 sb1=re.sub("[0-9]+","-","abc12de3f45GH")
63 print (sb1)
64 #abc-de-f-GH
65 
66 sb2=re.sub("[0-9]+","-","abc12de3f45GH",count=2)
67 print (sb2)
68 #'abc-de-f45GH'
69 
70 
71 '''
72 match
73 
74 search
75 findall
76 split
77 sub
78 這四種最經常使用,能夠查看練習其中的方法。
79 '''
re經常使用的方法實例

  

  最經常使用的匹配語法:

1
2
3
4
5
re.match 從頭開始匹配
re.search 匹配包含
re.findall 把全部匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符當作列表分隔符
re.sub      匹配字符並替換

  

  反斜槓的困擾:
  與大多數編程語言相同,正則表達式裏使用"\"做爲轉義字符,這就可能形成反斜槓困擾。

  假如你須要匹配文本中的字符"\",那麼使用編程語言表示的正則表達式裏將須要4個反斜槓"\\\\":前兩個和後兩個分別用於在編程語言裏轉義成反斜槓,轉換成兩個反斜槓後再在正則表達式裏轉義成一個反斜槓。

  Python裏的原生字符串很好地解決了這個問題,這個例子中的正則表達式可使用r"\\"表示。一樣,匹配一個數字的"\\d"能夠寫成r"\d"。有了原生字符串,你不再用擔憂是否是漏寫了反斜槓,寫出來的表達式也更直觀。  

 

  

  僅需輕輕知道的幾個匹配模式:

1
2
3
re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
M(MULTILINE): 多行模式,改變 '^' '$' 的行爲(參見上圖)
S(DOTALL): 點任意匹配模式,改變 '.' 的行爲

  實例練習1:

 1 #Author http://www.cnblogs.com/Jame-mei
 2 import re
 3 
 4 #1.re.I
 5 f1=re.search("[a-z]+","abcA",flags=re.I).group()
 6 print (f1)
 7 #輸出abcA,re.I能夠忽略大小寫輸出。
 8 
 9 
10 #2.re.M
11 m1=re.search(r"^a","\nabc\ncba")
12 #沒法匹配,爲空
13 m2=re.search(r"^abc","\nabc\ncba",flags=re.M).group()
14 print (m2)
15 #輸出 abc,忽略換行符,匹配
16 
17 
18 #3.re.S
19 s1=re.search(r".+","\nabc\ncba",flags=re.S).group()
20 print (s1)
21 #輸出abc cba,忽略了換行符!
re.I/M/S

 

  實例練習2:

  1 import re
  2 
  3 # print(re.findall('egon','helloegon123 -_egon*()'))
  4 #                                           egon
  5 # ['egon','egon']
  6 
  7 # print(re.findall('\w','hello123 -_*()'))
  8 #                                 \w
  9 # print(re.findall('\W','hello123 -_*()'))
 10 #                                   \W
 11 # print(re.findall('\s','h  \tell\nlo'))
 12 # print(re.findall('\S','h  \tell\nlo'))
 13 
 14 # print(re.findall('\d','hello123  456'))
 15 # print(re.findall('\D','hello*12-3 = 456'))
 16 
 17 # print(re.findall('\s','h  \tell\nlo'))
 18 # print(re.findall('\t','h  \tell\nlo'))
 19 # print(re.findall('\n','h  \tell\nlo'))
 20 
 21 # print(re.findall('egon','egon say hello egon egon is hahahah'))
 22 # print(re.findall('^egon','egon say hello egon egon is hahahah'))
 23 # print(re.findall('^egon',' egon say hello egon egon is hahahah'))
 24 # print(re.findall('alex$','hello alex aaa bb alex '))
 25 #                                            alex$
 26 
 27 # . :表明匹配除了換行符之外的任意單個字符
 28 # print(re.findall('a.c','a-c a*c a1c a\nc aaaaac a c'))
 29 #                                           a.c
 30 # print(re.findall('a.c','a-c a*c a1c a\nc aaaaac a c',re.DOTALL))
 31 # ['a-c','a*c','a1c','aac','a c']
 32 
 33 # []: 表明匹配咱們本身指定範圍的任意一個字符,
 34 # print(re.findall('\d[-+*/]\d','1+3 a1!3sdf 2*3 1/4 2-3 aadsf hello'))
 35 # print(re.findall('a[0-9]c','a1c a2c a11c abc a*c a9c'))
 36 # print(re.findall('a[0-9][0-9]c','a1c a2c a11c abc a*c a9c'))
 37 # print(re.findall('a[a-z]c','a1c aAc a2c acc aec a11c abc a*c a9c'))
 38 # print(re.findall('a[A-Z]c','a1c aAc a2c acc aec a11c abc a*c a9c'))
 39 # print(re.findall('a[A-Za-z]c','a1c aAc a2c acc aec a11c abc a*c a9c'))
 40 
 41 # 重複匹配
 42 # ? : 表明左邊那一個字符出現0次或者1次
 43 # print(re.findall('ab?','b ab abb abbbb bbbbbba'))
 44 #                                            ab?
 45 # ['ab','ab','ab','a']
 46 # print(re.findall('ab{0,1}','b ab abb abbbb bbbbbba'))
 47 
 48 
 49 # * :表明左邊那一個字符出現0次或者無窮次,若是沒有能夠湊合,但若是>1個,有多少就必須拿多少
 50 # print(re.findall('ab*','b ab abb abbbb bbbbbba'))
 51 #                                            ab*
 52 # ['ab','abb','abbbb','a']
 53 # print(re.findall('ab{0,}','b ab abb abbbb bbbbbba'))
 54 
 55 
 56 # + :表明左邊那一個字符出現1次或者無窮次,至少要有一個,但若是有>1個,有多少就必須拿多少
 57 # print(re.findall('ab+','b ab abb abbbb bbbbbba'))
 58 #                                           ab+
 59 # ['ab','abb','abbbb',]
 60 # print(re.findall('ab{1,}','b ab abb abbbb bbbbbba'))
 61 
 62 
 63 # {n,m}:表明左邊那一個字符出現n次到m次,至少要有n個,但若是有>n個,就拿<=m個
 64 # print(re.findall('ab{2,5}','b ab abbbbbbbbbbb abb abbbb bbbbbba'))
 65 #                                                      ab{2,5}
 66 # ['abbbbb','abb','abbbb',]
 67 
 68 
 69 # .* : 匹配0個或無窮個任意字符,默認是貪婪匹配
 70 # print(re.findall('a.*c','helloac a123lllc4a567+-1c egon')) #找離a最遠的那個c
 71 #                                                 a.*c
 72 
 73 # .*? : 匹配0個或無窮個任意字符,非貪婪匹配
 74 # print(re.findall('a.*?c','helloac a123lllc4a567+-1c egon')) #找離a最遠的那個c
 75 #                                          a.*?c
 76 # ['ac','a123lllc','a567+-1c']
 77 
 78 
 79 # print(re.findall('href="(.*?)"','<div class="div1"><a href="https://www.baidu.com">點我啊</a></div><div class="div1"><a href="https://www.python.org">點我啊</a></div>'))
 80 #                                                                                                                     href=".*"
 81 
 82 # print(re.findall('href="(.*?)"','<div class="div1"><a href="https://www.baidu.com">點我啊</a></div><div class="div1"><a href="https://www.python.org">點我啊</a></div>'))
 83 
 84 
 85 
 86 # print(re.findall('compan(ies|y)','Too many companies have gone bankrupt, and the next one is my company'))
 87 #                                                                                               compan(ies|y)
 88 # print(re.findall('compan(?:ies|y)','Too many companies have gone bankrupt, and the next one is my company'))
 89 
 90 # print(re.findall('a[^0-9]c','a1c abc aAc a-c a*c'))
 91 
 92 
 93 # print(re.findall('a\\\\c','a\c a1c aac')) #a\\c
 94 # print(re.findall(r'a\\c','a\c a1c aac')) #a\\c
 95 
 96 
 97 # print(re.findall(r'egon','egon is egon hhaha egon'))
 98 
 99 # 從左往右匹配,匹配成功一個就結束,返回一個對象,不成功最後返回None
100 # print(re.search(r'egon','egxxxon is egon hhaha egon'))
101 # print(re.search(r'xxx','egon is egon hhaha egon'))
102 
103 # print(re.search(r'egon','egxxxon is egon hhaha egon').group())
104 
105 # obj=re.search('(href)="(.*?)"','<div class="div1"><a href="https://www.baidu.com">點我啊</a></div><div class="div1"><a href="https://www.python.org">點我啊</a></div>')
106 # print(obj.group())
107 # print(obj.group(1))
108 # print(obj.group(2))
109 
110 
111 # print(re.search(r'xxxx','egxxxon is egon hhaha egon').group())
112 
113 
114 # print(re.search(r'^egon','egon egxxxon is egon hhaha egon'))
115 # print(re.match(r'egon','egon egxxxon is egon hhaha egon').group())
116 
117 
118 # msg='root:x:0:0::/root:/bin/bash'
119 # print(re.split('[:/]',msg))
120 
121 # print(re.sub('alex','sb','alex hello alex is sb alex'))
122 # print(re.sub('^alex','sb','alex hello alex is sb alex'))
123 # print(re.sub('alex$','sb','alex hello alex is sb alex'))
124 
125 obj=re.compile('href="(.*?)"')
126 
127 msg1='<div class="div1"><a href="https://www.baidu.com">點我啊</a></div><div class="div1"><a href="https://www.python.org">點我啊</a></div>'
128 # print(re.findall('href="(.*?)"',msg1))
129 print(obj.findall(msg1))
130 
131 msg2='<div class="div1"><a href="https://www.sina.com.cn">點我啊</a></div><div class="div1"><a href="https://www.tmall.com">點我啊</a></div>'
132 # print(re.search('href="(.*?)"',msg2).group(1))
133 print(obj.search(msg2).group(1))
課堂練習

  實例練習3:

# =================================匹配模式=================================
#一對一的匹配
# 'hello'.replace(old,new)
# 'hello'.find('pattern')

#正則匹配
import re
#\w與\W
print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
print(re.findall('\W','hello egon 123')) #[' ', ' ']

#\s與\S
print(re.findall('\s','hello  egon  123')) #[' ', ' ', ' ', ' ']
print(re.findall('\S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

#\n \t都是空,均可以被\s匹配
print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']

#\n與\t
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']

#\d與\D
print(re.findall('\d','hello egon 123')) #['1', '2', '3']
print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']

#\A與\Z
print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$

#^與$
print(re.findall('^h','hello egon 123')) #['h']
print(re.findall('3$','hello egon 123')) #['3']

# 重複匹配:| . | * | ? | .* | .*? | + | {n,m} |
#.
print(re.findall('a.b','a1b')) #['a1b']
print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb']
print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一條意思同樣

#*
print(re.findall('ab*','bbbbbbb')) #[]
print(re.findall('ab*','a')) #['a']
print(re.findall('ab*','abbbb')) #['abbbb']

#?
print(re.findall('ab?','a')) #['a']
print(re.findall('ab?','abbb')) #['ab']
#匹配全部包含小數在內的數字
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']

#.*默認爲貪婪匹配
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']

#.*?爲非貪婪匹配:推薦使用
print(re.findall('a.*?b','a1b22222222b')) #['a1b']

#+
print(re.findall('ab+','a')) #[]
print(re.findall('ab+','abbb')) #['abbb']

#{n,m}
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'

#[]
print(re.findall('a[1*-]b','a1b a*b a-b')) #[]內的都爲普通字符了,且若是-沒有被轉意的話,應該放到[]的開頭或結尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]內的^表明的意思是取反,因此結果爲['a=b']
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]內的^表明的意思是取反,因此結果爲['a=b']

#\# print(re.findall('a\\c','a\c')) #對於正則來講a\\c確實能夠匹配到a\c,可是在python解釋器讀取a\\c時,會發生轉義,而後交給re去執行,因此拋出異常
print(re.findall(r'a\\c','a\c')) #r表明告訴解釋器使用rawstring,即原生字符串,把咱們正則內的全部符號都當普通字符處理,不要轉義
print(re.findall('a\\\\c','a\c')) #同上面的意思同樣,和上面的結果同樣都是['a\\c']

#():分組
print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的結果不是匹配的所有內容,而是組內的內容,?:可讓結果爲匹配的所有內容
print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">點擊</a>'))#['http://www.baidu.com']
print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">點擊</a>'))#['href="http://www.baidu.com"']

#|
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
重點練習

  

  re其餘方法介紹:

# ===========================re模塊提供的方法介紹===========================
import re
#1
print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回全部知足匹配條件的結果,放在列表裏
#2
print(re.search('e','alex make love').group()) #e,只到找到第一個匹配而後返回一個包含匹配信息的對象,該對象能夠經過調用group()方法獲得匹配的字符串,若是字符串沒有匹配,則返回None。

#3
print(re.match('e','alex make love'))    #None,同search,不過在字符串開始處進行匹配,徹底能夠用search+^代替match

#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割獲得''和'bcd',再對''和'bcd'分別按'b'分割

#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默認替換全部
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex

print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),結果帶有總共替換的個數


#6
obj=re.compile('\d{2}')

print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj
re其餘方法介紹

 

  補充1:

import re
print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1']
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>

print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group())
print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group())

補充一
re補充1

  補充2:

import re

print(re.findall(r'-?\d+\.?\d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出全部數字['1', '-12', '60', '-40.35', '5', '-4', '3']


#使用|,先匹配的先生效,|左邊是匹配小數,而findall最終結果是查看分組,全部即便匹配成功小數也不會存入結果
#而不是小數時,就去匹配(-?\d+),匹配到的天然就是,非小數的數,在此處即整數
print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出全部整數['1', '-2', '60', '', '5', '-4', '3']

補充二
re補充2

 

 

 

本週做業:

開發一個簡單的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等相似功能偷懶實現),運算後得出結果,結果必須與真實的計算器所得出的結果一致

 

做業源碼地址:https://gitee.com/meijinmeng/calculator.git 

相關文章
相關標籤/搜索