[TOC]python
反射:利用字符串的形式去對象(默認)中操做(尋找)成員
cat commons.py
正則表達式
#!/usr/bin/env python #_*_coding:utf-8_*_ ''' * Created on 2016/12/3 21:54. * @author: Chinge_Yang. ''' def login(): print("炫酷登陸") def home(): print("炫酷頁面") def logout(): print("歡樂退出")
cat index.py
算法
#!/usr/bin/env python #_*_coding:utf-8_*_ ''' * Created on 2016/12/3 21:56. * @author: Chinge_Yang. ''' import commons def run(): if hasattr(commons, inp): inp = input("請輸入要訪問的url:") func = getattr(commons, inp) func() else: print("404") if __name__ == "__main__": run()
以字符串方式導入模塊:shell
obj = __import__("commons") obj = __import__("commons.login", fromlist = True)
實例實質:僞造Web框架的路由系統
getattr,delattr,setattr,hasattr編程
模塊中的特殊變量:緩存
print(__doc__) #獲取文件開頭的註釋,(3個引號中間的信息) __cache__ #緩存pyc存放的位置 print(__file__) #當前py文件所在的路徑 os.path.abspath() #獲取文件的絕對路徑 os.path.dirname() #獲取文件目錄的名字 sys.path.append(os.path.dirname(os.path.abspath(__file__))) #添加文件上層目錄到python庫 print(admin.__packages__) #獲取admin所在的包名 #只有執行當前文件時,當前文件的特殊變量__name__ == "__main__"
用於提供對Python解釋器相關的操做:bash
sys.argv 命令行參數List,第一個元素是程序自己路徑 sys.exit(n) 退出程序,正常退出時exit(0) sys.version 獲取Python解釋程序的版本信息 sys.maxint 最大的Int值 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform 返回操做系統平臺名稱 sys.stdin 輸入相關 sys.stdout 輸出相關 sys.stderror 錯誤相關
進度條案例:app
#!/usr/bin/env python # _*_coding:utf-8_*_ ''' * Created on 2016/12/4 10:53. * @author: Chinge_Yang. ''' import sys import time def view_bar(num, total): rate = num / total rate_num = int(rate * 100) #r = '\r%d%%' % (rate_num, ) r = '\r%s>%d%%' % (">" * num, rate_num) sys.stdout.write(r) sys.stdout.flush() if __name__ == '__main__': for i in range(0, 100): time.sleep(0.1) view_bar(i, 100)
用於提供系統級別的操做:框架
os.getcwd() 獲取當前工做目錄,即當前python腳本工做的目錄路徑 os.chdir("dirname") 改變當前腳本工做目錄;至關於shell下cd os.curdir 返回當前目錄: ('.') os.pardir 獲取當前目錄的父目錄字符串名:('..') os.makedirs('dir1/dir2') 可生成多層遞歸目錄 os.removedirs('dirname1') 若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推 os.mkdir('dirname') 生成單級目錄;至關於shell中mkdir dirname os.rmdir('dirname') 刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印 os.remove() 刪除一個文件 os.rename("oldname","new") 重命名文件/目錄 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所指向的文件或者目錄的最後修改時間
用於加密相關的操做,代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法編程語言
import hashlib # ######## md5 ######## hash = hashlib.md5() # help(hash.update) hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) print(hash.digest()) ######## sha1 ######## hash = hashlib.sha1() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) 以上加密算法雖然依然很是厲害,但時候存在缺陷,即:經過撞庫能夠反解。因此,有必要對加密算法中添加自定義key再來作加密。 import hashlib # ######## md5 ######## hash = hashlib.md5(bytes('ygqygq2',encoding="utf-8")) hash.update(bytes('admin',encoding="utf-8")) print(hash.hexdigest()) python內置還有一個 hmac 模塊,它內部對咱們建立 key 和 內容 進行進一步的處理而後再加密 import hmac h = hmac.new(bytes('ygqygq2',encoding="utf-8")) h.update(bytes('admin',encoding="utf-8")) print(h.hexdigest())
簡介: 就其本質而言,正則表達式(或re)是一種小型的、高度專業化的編程語言,(在Python中)它內嵌在Python中,並經過re模塊實現。正則表達式模式被編譯成一系列的字節碼,而後由用C編寫的匹配引擎執行。
字符: . 匹配除換行符之外的任意字符 \w 匹配字母或數字或下劃線或漢字 \s 匹配任意的空白符 \d 匹配數字 \b 匹配單詞的開始或結束 ^ 匹配字符串的開始 $ 匹配字符串的結束
次數: * 重複零次或更屢次 + 重複一次或更屢次 ? 重複零次或一次 {n} 重複n次 {n,} 重複n次或更屢次 {n,m} 重複n到m次
Python提供re模塊,包含全部正則表達式的功能。因爲Python的字符串自己也用\轉義,因此要特別注意:
s = 'ABC\\-001' # Python的字符串 # 對應的正則表達式字符串變成: # 'ABC\-001'
所以咱們強烈建議使用Python的r前綴,就不用考慮轉義的問題了:
s = r'ABC\-001' # Python的字符串 # 對應的正則表達式字符串不變: # 'ABC\-001'
先看看如何判斷正則表達式是否匹配:
>>> import re >>> re.match(r'^\d{3}\-\d{3,8}$', '010-12345') <_sre.SRE_Match object; span=(0, 9), match='010-12345'> >>> re.match(r'^\d{3}\-\d{3,8}$', '010 12345') >>>
分組
除了簡單地判斷是否匹配以外,正則表達式還有提取子串的強大功能。用()表示的就是要提取的分組(Group)。好比:
^(\d{3})-(\d{3,8})$分別定義了兩個組,能夠直接從匹配的字符串中提取出區號和本地號碼:
>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345') >>> m <_sre.SRE_Match object; span=(0, 9), match='010-12345'> >>> m.group(0) '010-12345' >>> m.group(1) '010' >>> m.group(2) '12345'
若是正則表達式中定義了組,就能夠在Match對象上用group()方法提取出子串來。 注意到group(0)永遠是原始字符串,group(1)、group(2)……表示第一、二、……個子串。 提取子串很是有用。來看一個更兇殘的例子:
>>> t = '19:05:30' >>> m = re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t) >>> m.groups() ('19', '05', '30')
這個正則表達式能夠直接識別合法的時間。可是有些時候,用正則表達式也沒法作到徹底驗證,好比識別日期: '^(0[1-9]|1[0-2]|[0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[0-9])$'
對於'2-30','4-31'這樣的非法日期,用正則仍是識別不了,或者說寫出來很是困難,這時就須要程序配合識別了。
編譯
當咱們在Python中使用正則表達式時,re模塊內部會幹兩件事情: 編譯正則表達式,若是正則表達式的字符串自己不合法,會報錯; 用編譯後的正則表達式去匹配字符串。 若是一個正則表達式要重複使用幾千次,出於效率的考慮,咱們能夠預編譯該正則表達式,接下來重複使用時就不須要編譯這個步驟了,直接匹配:
>>> import re # 編譯: >>> re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$') # 使用: >>> re_telephone.match('010-12345').groups() ('010', '12345') >>> re_telephone.match('010-8086').groups() ('010', '8086')
match
# match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回None match(pattern, string, flags=0) # pattern: 正則模型 # string : 要匹配的字符串 # falgs : 匹配模式 X VERBOSE Ignore whitespace and comments for nicer looking RE's. I IGNORECASE Perform case-insensitive matching. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns.
實例:
# 無分組 r = re.match("h\w+", origin) print(r.group()) # 獲取匹配到的全部結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組結果 # 有分組 # 爲什麼要有分組?提取匹配成功的指定內容(先匹配成功所有正則,再匹配成功的局部內容提取出來) r = re.match("h(\w+).*(?P<name>\d)$", origin) print(r.group()) # 獲取匹配到的全部結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組中全部執行了key的組
search
# search,瀏覽整個字符串去匹配第一個,未匹配成功返回None # search(pattern, string, flags=0)
實例:
# 無分組 r = re.search("a\w+", origin) print(r.group()) # 獲取匹配到的全部結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組結果 # 有分組 r = re.search("a(\w+).*(?P<name>\d)$", origin) print(r.group()) # 獲取匹配到的全部結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組中全部執行了key的組
findall
# findall,獲取非重複的匹配列表;若是有一個組則以列表形式返回,且每個匹配均是字符串;若是模型中有多個組,則以列表形式返回,且每個匹配均是元祖; # 空的匹配也會包含在結果中 #findall(pattern, string, flags=0)
實例:
# 無分組 r = re.findall("a\w+",origin) print(r) # 有分組 origin = "hello alex bcd abcd lge acd 19" r = re.findall("a((\w*)c)(d)", origin) print(r)
sub
# sub,替換匹配成功的指定位置字符串 sub(pattern, repl, string, count=0, flags=0) # pattern: 正則模型 # repl : 要替換的字符串或可執行對象 # string : 要匹配的字符串 # count : 指定匹配個數 # flags : 匹配模式
實例:
# 與分組無關 origin = "hello alex bcd alex lge alex acd 19" r = re.sub("a\w+", "999", origin, 2) print(r)
split
# split,根據正則匹配分割字符串 split(pattern, string, maxsplit=0, flags=0) # pattern: 正則模型 # string : 要匹配的字符串 # maxsplit:指定分割個數 # flags : 匹配模式
實例:
# 無分組 origin = "hello alex bcd alex lge alex acd 19" r = re.split("alex", origin, 1) print(r) # 有分組 origin = "hello alex bcd alex lge alex acd 19" r1 = re.split("(alex)", origin, 1) print(r1) r2 = re.split("(al(ex))", origin, 1) print(r2)
經常使用正則表達式:
IP: ^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$ 手機號: ^1[3|4|5|8][0-9]\d{8}$ 郵箱: [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+