- 模塊介紹
- time &datetime模塊
- random
- os
- sys
- shutil
- shelve
- xml處理
- yaml處理
- configparser
- hashlib
- re正則表達式
- logging模塊
1、模塊:
定義:其實模塊簡單說就是一堆代碼實現某個功能,它們是已經寫好的.py文件。只需要用import應用即可。
分類:
1、自定義模塊
2、內置標准模塊(又稱標准庫)
3、開源模塊
1、自定義模塊,就是自己寫的.py文件為了實現某個功能。
2、內置模塊,就是python自身已經寫好的某個功能,例如經常用的sys、os等模塊都是內置模塊。
3、開源模塊,開源大家都明白吧,就是不收費的別人寫好的模塊,一般也稱第三方模塊。
模塊的引用:
1、import modules
2、from modules import 函數
3、如果有多個模塊,可以用逗號隔開,如果想把某個模塊里面的所有功能都導入,可以用*,這樣的話功能都加載道內存里面,占用內存資源,不建議用。
2、time &datetime模塊
1 #!/usr/bin/env python 2 #—*—coding:utf-8—*— 3 4 # time和datetime 5 6 import time,datetime 7 8 9 ###time 10 # print(time.process_time())#返回處理器時間,3.3開始已廢棄 , 改成了time.process_time()測量處理器運算時間,不包括sleep時間,不穩定,mac上測不出來 11 # >>>0.09375 12 13 # print(time.altzone)#返回與utc時間的時間差,以秒計算\ 14 # >>>-32400 15 16 # print(time.asctime()) #返回時間格式"Mon Aug 22 09:31:43 2016", 17 # >>>Mon Aug 22 09:31:43 2016 18 19 20 # print(time.localtime()) 21 # >>>time.struct_time(tm_year=2016, tm_mon=8, tm_mday=22, tm_hour=9, tm_min=32, tm_sec=28, tm_wday=0, tm_yday=235, tm_isdst=0) 22 #tm_year(年),tm_mon(月),tm_mday(日),tm_hour(時),tm_min(分),tm_sec(秒),tm_wday(星期,從0到6,0代表周一,一次類推),tm_yday(這一年中的地幾天),tm_isdst(夏令時間標志) 23 24 25 # print(time.time())#(獲取時間戳) 26 # a = time.time() 27 # b = a/3600/24/365 28 # print(b) 29 # >>>46.67149458666888 30 # 2016-1970 31 # >>>46 32 #時間是村1970年開始算,為什么時間要從1970年開始算呢 33 #1970年1月1日 算 UNIX 和 C語言 生日. 由於主流計算機和操作系統都用它,其他儀器,手機等也就用它了. 34 35 36 37 # print(time.gmtime(time.time()-800000))#返回utc時間的struc時間對象格式 38 # >>>time.struct_time(tm_year=2016, tm_mon=8, tm_mday=12, tm_hour=20, tm_min=9, tm_sec=14, tm_wday=4, tm_yday=225, tm_isdst=0) 39 40 41 # print(time.asctime(time.localtime())) 42 # >>>Mon Aug 22 10:23:52 2016 43 # print(time.ctime()) 44 # >>>Mon Aug 22 10:24:25 2016 45 46 47 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d")#將時間字符串轉換成struct時間對象格式 48 # print(string_2_struct) 49 # >>>time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1) 50 51 52 # string_3_struct = time.strptime("2016/05/22","%Y/%m/%d") 53 # struct_2_stamp = time.mktime(string_3_struct) #將struct時間對象轉成時間戳 54 # print(struct_2_stamp) 55 # >>>1463846400.0 56 57 58 #print(time.gmtime(time.time()-86640))##將utc時間戳轉換成struct_time格式 59 #>>>time.struct_time(tm_year=2016, tm_mon=8, tm_mday=21, tm_hour=2, tm_min=25, tm_sec=14, tm_wday=6, tm_yday=234, tm_isdst=0) 60 61 # a = time.timezone 62 # print(a/3600) 63 # >>>-8.0東八區 64 65 # time.sleep()#睡幾秒 66 67 # time.localtime()#當前本地時間 68 69 70 #strftime()#重要! 71 # a = time.localtime()#將本地時間格式化 72 # time = time.strftime("%Y/%m/%d %H:%M:%S",a) 73 # print(time) 74 # >>>2016/08/22 10:31:07 75 # 前 76 # 前后剛好相反 77 # 后 78 # # time.strptime()#前后一定要位置一一對應(注意符號空格) 79 # time1 = time.strptime("2016-08:20 14:31:52","%Y-%m:%d %H:%M:%S") 80 # print(time1) 81 82 83 #####datetime(時間的加減) 84 85 # print(datetime.datetime.now()) #返回 2016-08-22 10:33:53.290793 86 87 # print(datetime.date.fromtimestamp(time.time()) ) #2016-08-22 88 89 # print(datetime.datetime.now() )#2016-08-22 10:34:37.885578當前時間一般使用這個 90 91 # print(datetime.datetime.now() + datetime.timedelta(3)) #當前時間+3天#2016-08-25 10:35:38.554216 92 93 # print(datetime.datetime.now() + datetime.timedelta(-3)) #當前時間-3天#2016-08-19 10:35:58.064103 94 95 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當前時間+3小時#2016-08-22 13:36:16.540940 96 97 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當前時間+30分#2016-08-22 11:06:34.837476 98 99 # c_time = datetime.datetime.now() 100 # print(c_time.replace(minute=3,hour=2)) #時間替換

3、random
1 #!/usr/bin/env python 2 #—*—coding:utf-8—*— 3 4 import random 5 6 #隨機數 7 # print(random.random())#0到的隨機數,是一個float浮點數 8 # print(random.randint(1,2))#一和二隨機 9 # print(random.randrange(1,10))#一到十隨機(記得range只有頭沒有尾巴) 10 # 11 # 生成隨機驗證碼 12 # 13 # checkcode='' 14 # for i in range(5): 15 # current = random.randrange(0,5) 16 # if current == i: 17 # tmp = chr(random.randint(65,90))#chr是ascii碼表,65,90是(A-Z) 18 # else: 19 # tmp = random.randint(0,9) 20 # checkcode +=str(tmp) 21 # print(checkcode) 22 23 24 #二般 25 import string 26 # print(''.join(random.sample(string.ascii_lowercase+string.digits,5)))#隨機驗證碼可用(5位含數字和密碼) 27 # 28 # print(''.join(random.sample(string.ascii_lowercase+string.digits,5)))#隨機驗證碼可用(5位含數字和密碼) 29 # 30 # #打印a-z 31 # print(string.ascii_lowercase)#一 32 # #打印A-Z 33 # print(string.ascii_letters)#二
4、os
1 #!/usr/bin/env python 2 # import os 3 # # print(os.getcwd())#打印當前目錄 4 # os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑 5 # os.chdir("dirname") 改變當前腳本工作目錄;相當於shell下cd 6 # os.curdir 返回當前目錄: ('.') 7 # os.pardir 獲取當前目錄的父目錄字符串名:('..') 8 # os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄 9 # os.removedirs('dirname1') 若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推 10 # os.mkdir('dirname') 生成單級目錄;相當於shell中mkdir dirname 11 # os.rmdir('dirname') 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname 12 # os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印 13 # os.remove() 刪除一個文件 14 # os.rename("oldname","newname") 重命名文件/目錄 15 # os.stat('path/filename') 獲取文件/目錄信息 16 # os.sep 輸出操作系統特定的路徑分隔符,win下為"\\",Linux下為"/" 17 # os.linesep 輸出當前平台使用的行終止符,win下為"\t\n",Linux下為"\n" 18 # os.pathsep 輸出用於分割文件路徑的字符串 19 # os.name 輸出字符串指示當前使用平台。win->'nt'; Linux->'posix' 20 # os.system("bash command") 運行shell命令,直接顯示 21 # os.environ 獲取系統環境變量 22 # os.path.abspath(path) 返回path規范化的絕對路徑 23 # os.path.split(path) 將path分割成目錄和文件名二元組返回 24 # os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素 25 # os.path.basename(path) 返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素 26 # os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False 27 # os.path.isabs(path) 如果path是絕對路徑,返回True 28 # os.path.isfile(path) 如果path是一個存在的文件,返回True。否則返回False 29 # os.path.isdir(path) 如果path是一個存在的目錄,則返回True。否則返回False 30 # os.path.join(path1[, path2[, ...]]) 將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略 31 # os.path.getatime(path) 返回path所指向的文件或者目錄的最后存取時間 32 # os.path.getmtime(path) 返回path所指向的文件或者目錄的最后修改時間 33 34 #更多 35 #https://docs.python.org/2/library/os.html?highlight=os#module-os
5、sys
1 #!/usr/bin/env python 2 #—*—coding:utf-8—*— 3 import sys 4 # print(sys.argv ) #命令行參數List,第一個元素是程序本身路徑 5 #>>>['E:/python/day5/sys(1).py'] 6 7 # sys.exit(n) #退出程序,正常退出時exit(0) 8 9 # print(sys.version ) #獲取Python解釋程序的版本信息 10 # >>>3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] 11 12 # print(sys.maxint) #最大的Int值 13 # sys.path #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 14 # print(sys.platform) #返回操作系統平台名稱 15 # >>>win32 16 17 # print(sys.stdout.write('please:')) 18 # >>>please:7 19 20 # val = sys.stdin.readline()[:-1]
6、shutil
1 #!/usr/bin/env python 2 import shutil 3 4 5 # shutil.copyfileobj(fsrc, fdst[, length]) 6 # 將文件內容拷貝到另一個文件中,可以部分內容 7 8 # shutil.copyfile(src, dst) 9 # 拷貝文件 10 11 # shutil.copymode(src, dst) 12 # 僅拷貝權限。內容、組、用戶均不變 13 14 # shutil.copystat(src, dst) 15 # 拷貝狀態的信息,包括:mode bits, atime, mtime, flags 16 17 # shutil.copy(src, dst) 18 # 拷貝文件和權限 19 20 21 # shutil.copy2(src, dst) 22 # 拷貝文件和狀態信息 23 24 25 # shutil.rmtree(path[, ignore_errors[, onerror]]) 26 # 遞歸的去刪除文件 27 28 # shutil.move(src, dst) 29 # 遞歸的去移動文件(刪除文件) 30 31 32 shutil.make_archive(base_name, format,...) 33 34 創建壓縮包並返回文件路徑,例如:zip、tar 35 36 base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑, 37 如:www =>保存至當前路徑 38 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ 39 format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar” 40 root_dir: 要壓縮的文件夾路徑(默認當前目錄) 41 owner: 用戶,默認當前用戶 42 group: 組,默認當前組 43 logger: 用於記錄日志,通常是logging.Logger對象 44 45 #將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄 46 47 import shutil 48 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') 49 50 51 #將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄 52 import shutil 53 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
7、shelve
1 import shelve 2 d = shelve.open('shelve_test') 3 4 #寫 5 # name = {"zhangsan","lisi","wanger"} 6 # info = {"age":25,"job":"IT"} 7 # d["name"] = name 8 # d["info"] = info 9 # d.close() 10 #寫完以后,它會自動生成三個文件,.dat和.dir和.bak 11 12 #讀 13 # print(d.get("name")) 14 # print(d.get("info"))
8、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>
1 #!/usr/bin/env python 2 #—*—coding:utf-8—*— 3 4 import xml.etree.ElementTree as ET 5 6 tree = ET.parse("xml.xml") 7 root = tree.getroot() 8 print(root.tag) 9 10 #遍歷xml文檔 11 # for child in root: 12 # print(child.tag, child.attrib) 13 # for i in child: 14 # print(i.tag,i.text) 15 #>>>結果 16 # data 17 # country {'name': 'Liechtenstein'} 18 # rank 2 19 # year 2008 20 # gdppc 141100 21 # neighbor None 22 # neighbor None 23 # country {'name': 'Singapore'} 24 # rank 5 25 # year 2011 26 # gdppc 59900 27 # neighbor None 28 # country {'name': 'Panama'} 29 # rank 69 30 # year 2011 31 # gdppc 13600 32 # neighbor None 33 # neighbor None 34 35 36 37 #只遍歷year 節點 38 # for node in root.iter('year'): 39 # print(node.tag,node.text) 40 # >>>data 41 # >>>year2008 42 # >>>year 2011 43 # >>>year 2011
9、yaml處理
yaml和xml差不多,只是需要自己安裝一個模塊,參考鏈接:參考文檔:http://pyyaml.org/wiki/PyYAMLDocumentation
10、configparser
這個比較好玩一點,大家多知道mysql配置文件my.cnf文件的格式吧
1 #類似這樣的配置文件,一塊一塊的分類 2 [DEFAULT] 3 ServerAliveInterval = 45 4 Compression = yes 5 CompressionLevel = 9 6 ForwardX11 = yes 7 8 [bitbucket.org] 9 User = hg 10 11 [topsecret.server.com] 12 Port = 50022 13 ForwardX11 = no
1 #生成類似格式的文件 2 import configparser 3 4 config = configparser.ConfigParser() 5 config["DEFAULT"] = {'ServerAliveInterval': '45', 6 'Compression': 'yes', 7 'CompressionLevel': '9'} 8 9 config['bitbucket.org'] = {} 10 config['bitbucket.org']['User'] = 'hg' 11 config['topsecret.server.com'] = {} 12 topsecret = config['topsecret.server.com'] 13 topsecret['Host Port'] = '50022' # mutates the parser 14 topsecret['ForwardX11'] = 'no' # same here 15 config['DEFAULT']['ForwardX11'] = 'yes' 16 with open('example.ini', 'w') as configfile: 17 config.write(configfile)
1 #讀 2 # import configparser 3 # config = configparser.ConfigParser() 4 # config.sections() 5 # 6 # config.read('example.ini') 7 # 8 # print(config.defaults()) 9 # >>>OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45'), ('forwardx11', 'yes')]) 10 # print(config['bitbucket.org']["User"]) 11 # >>>hg 12 # print(config["topsecret.server.com"]["host port"]) 13 # 50022
1 #刪除(創建一個新文件,並刪除bitbucket.org) 2 import configparser 3 config = configparser.ConfigParser() 4 config.sections() 5 6 config.read('example.ini') 7 rec = config.remove_section("bitbucket.org")#刪除該項 8 config.write(open("example.cfg","w")) 9 [DEFAULT] 10 compressionlevel = 9 11 compression = yes 12 serveraliveinterval = 45 13 forwardx11 = yes 14 15 [topsecret.server.com] 16 host port = 50022 17 forwardx11 = no
11、hashlib
1 #!/usr/bin/env python 2 3 import hashlib 4 5 # m = hashlib.md5() 6 # m.update(b"hello") 7 # print(m.digest())#進行二進制加密 8 # print(len(m.hexdigest())) #16進制長度 9 # print(m.hexdigest())#16進制格式hash 10 # >>>b']A@*\xbcK*v\xb9q\x9d\x91\x10\x17\xc5\x92' 11 # >>>32 12 # >>>5d41402abc4b2a76b9719d911017c592 13 14 15 #md5 16 # hash = hashlib.md5() 17 # hash.update(('admin').encode()) 18 # print(hash.hexdigest()) 19 # >>>21232f297a57a5a743894a0e4a801fc3 20 21 22 #sha1 23 # hash = hashlib.sha1() 24 # hash.update(('admin').encode()) 25 # print(hash.hexdigest()) 26 # >>>d033e22ae348aeb5660fc2140aec35850c4da997 27 28 #sha256 29 # hash = hashlib.sha256() 30 # hash.update(('admin').encode()) 31 # print(hash.hexdigest()) 32 # >>>8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918 33 34 35 36 #sha384 37 # hash = hashlib.sha384() 38 # hash.update(('admin').encode()) 39 # print(hash.hexdigest()) 40 # >>>9ca694a90285c034432c9550421b7b9dbd5c0f4b6673f05f6dbce58052ba20e4248041956ee8c9a2ec9f10290cdc0782 41 42 43 #sha512 44 # hash = hashlib.sha512() 45 # hash.update(('admin').encode()) 46 # print(hash.hexdigest()) 47 # >>>c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec 48 49 50 #更吊的 51 import hmac 52 h = hmac.new(('wueiqi').encode()) 53 h.update(('hellowo').encode()) 54 print(h.hexdigest()) 55 #更多關於md5,sha1,sha256等介紹的文章看這里https://www.tbs-certificates.co.uk/FAQ/en/sha256.html
12、re正則表達式
1 # #!/usr/bin/env python 2 # 3 # '.' 默認匹配除\n之外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行 4 # '^' 匹配字符開頭,若指定flags MULTILINE,這種也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) 5 # '$' 匹配字符結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以 6 # '*' 匹配*號前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 結果為['abb', 'ab', 'a'] 7 # '+' 匹配前一個字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb'] 8 # '?' 匹配前一個字符1次或0次 9 # '{m}' 匹配前一個字符m次 10 # '{n,m}' 匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb'] 11 # '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC' 12 # '(...)' 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c 13 # 14 # 15 # '\A' 只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的 16 # '\Z' 匹配字符結尾,同$ 17 # '\d' 匹配數字0-9 18 # '\D' 匹配非數字 19 # '\w' 匹配[A-Za-z0-9] 20 # '\W' 匹配非[A-Za-z0-9] 21 # 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t' 22 # 23 # '(?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'} 24 25 26 #常用的匹配方法 27 # re.match 從頭開始匹配 28 # re.search 匹配包含 29 # re.findall 把所有匹配到的字符放到以列表中的元素返回 30 # re.splitall 以匹配到的字符當做列表分隔符 31 # re.sub 匹配字符並替換 32 33 # 僅需輕輕知道的幾個匹配模式 34 # 35 # re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同) 36 # M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖) 37 # S(DOTALL): 點任意匹配模式,改變'.'的行為
re.match是從頭開始的
1 #正則表達式的練習 2 import re 3 >>> re.match("^baidu","baidu.com") 4 <_sre.SRE_Match object; span=(0, 5), match='baidu'>#match就是匹配到的結果,如果沒有返回,就證明沒有匹配到
1 >>> ret = re.match("^www\d","www123baidu456")#一個\d表示匹配后面的一個數字 2 >>> ret.group() 3 'www1' 4 >>> ret = re.match("^www\d+","www123baidu456")#加上一個+代表匹配后面緊跟着的所有數字 5 >>> ret.group() 6 'www123'#如果沒有就是None
1 >>> re.match(".","www123baidu456")#匹配一個字符 2 <_sre.SRE_Match object; span=(0, 1), match='w'> 3 >>> re.match(".+","www123baidu456")#加上一個加就匹配所有了 4 <_sre.SRE_Match object; span=(0, 14), match='www123baidu456'>
re.search
1 >>> re.match(".","www123baidu456")#語法二,查找 2 <_sre.SRE_Match object; span=(0, 1), match='w'> 3 >>> re.match(".+","www123baidu456") 4 <_sre.SRE_Match object; span=(0, 14), match='www123baidu456'>
1 >>> re.search("@.+@$","123@baidu@")#匹配某個關鍵字中間(包含關鍵字) 2 <_sre.SRE_Match object; span=(3, 10), match='@baidu@'>
1 ?#匹配次或0次
1 re.search("b?","bbbaidu") 2 <_sre.SRE_Match object; span=(0, 1), match='b'> 3 >>> re.search("b?","aidu")#?前面的可以有,也可以沒有,沒有就匹配后面的 4 <_sre.SRE_Match object; span=(0, 0), match=''>
1 >>> re.search("[0-9]{4}","daf123bbbk4567")#{4}代表連續幾個數字 2 <_sre.SRE_Match object; span=(10, 14), match='4567'>
換個套路,如果我想匹配字符串里面所有的數字或者字母呢
1 >>> re.findall("[0-9]{1,3}","daf34dkafjl675kdla98dfasfa536") 2 ['34', '675', '98', '536'] 3 4 >>> re.findall("[0-9]{1,2}","daf34dkafjl675kdla98dfasfa536") 5 ['34', '67', '5', '98', '53', '6'] 6 7 8 >>> re.findall("[0-9]{1,5}","daf34dkafjl675kdla98dfasfa536") 9 ['34', '675', '98', '536'] 10 11 12 >>> re.findall("[0-9]{1}","daf34dkafjl675kdla98dfasfa536") 13 ['3', '4', '6', '7', '5', '9', '8', '5', '3', '6'] 14 15 16 >>> re.findall("[0-9]{1,4}","daf34dkafjl675kdla98dfasfa536") 17 ['34', '675', '98', '536']
>>> re.findall("[0-9]{3}","daf34dkafjl675kdla98dfasfa536")
['675', '536']
1 #換個方法|(或) 2 >>> re.search("abc|ABC","ABCabc").group() 3 'ABC' 4 >>> re.findall("abc|ABC","ABCabc") 5 ['ABC', 'abc']
1 #分組匹配 2 >>> re.search("(abc){2}","ddddabccdfabc")#需要連續兩個abc才能匹配到,見下面 3 >>> re.search("(abc){2}","ddddabcabc") 4 <_sre.SRE_Match object; span=(4, 10), match='abcabc'>
#轉意符 >>> re.search("(abc){2}\|","ddddabcabc|")#告訴python管道符在這里不是管道符就是一個豎杠用\轉意 <_sre.SRE_Match object; span=(4, 11), match='abcabc|'>
#分組轉意 >>> re.search("(abc){2}\|\|=","ddddabcabc||=") <_sre.SRE_Match object; span=(4, 13), match='abcabc||='> >>> re.search("(abc){2}(\|\|=){2}","ddddabcabc||=||=")#還是因為管道符在正則表達式里面是或的意思,兩個管道符都需要轉意 <_sre.SRE_Match object; span=(4, 16), match='abcabc||=||='>
1 #分割split 2 >>> re.split("[0-9]","abc123dfe456gjkd") 3 ['abc', '', '', 'dfe', '', '', 'gjkd'] 4 >>> re.split("[0-9]+","abc123dfe456gjkd") 5 ['abc', 'dfe', 'gjkd']
#sub替換 >>> re.sub("[0-9]","|","abc123dfe456gjkd") 'abc|||dfe|||gjkd' >>> re.sub("[0-9]","|","abc123dfe456gjkd",count=2) 'abc||3dfe456gjkd'
#反斜杠\ >>> re.search(r"\\","jdkafkdl\\dafd") <_sre.SRE_Match object; span=(8, 9), match='\\'>
#re.I#忽略大小寫 >>> re.search("[a-z]+","abcdHJ",flags=re.I) <_sre.SRE_Match object; span=(0, 6), match='abcdHJ'> #多行模式flags = re.m(匹配去掉換行繼續匹配\n不) >>> re.search("[a-z]+","\nabcdHJ",flags=re.M) <_sre.SRE_Match object; span=(1, 5), match='abcd'> #匹配任意字符 >>> re.search(".+","\nabcdHJ",flags=re.S) <_sre.SRE_Match object; span=(0, 7), match='\nabcdHJ'>
13、logging模塊
用於便捷記錄日志且線程安全的模塊
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
日志等級:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0
注意:只有大於當前日志等級的操作才會被記錄。
日志格式:
%(name)s:Logger的名字
%(levelno)s:數字形式的日志級別
%(levelname)s:文本形式的日志級別
%(pathname)s:調用日志輸出函數的模塊的完整路徑名,可能沒有
%(filename)s:調用日志輸出函數的模塊的文件名
%(module)s:調用日志輸出函數的模塊名
%(funcName)s:調用日志輸出函數的函數名
%(lineno)d:調用日志輸出函數的語句所在的代碼行
%(created)f:當前時間,用UNIX標准的表示時間的浮 點數表示
%(relativeCreated)d:輸出日志信息時的,自Logger創建以 來的毫秒數
%(asctime)s:字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
%(thread)d:線程ID。可能沒有
%(threadName)s:線程名。可能沒有
%(process)d:進程ID。可能沒有
%(message)s:用戶輸出的消息

