標籤:str python 檔案 程式設計 多次 左右 字元 port 管道
一.re模組
Regex時電腦科學的一個概念,Regex通常被用來檢索,替換那些符合某個模式的文本,大多數程式設計語言都支援利用Regex進行字串操作.
正則就是用一些具有特殊含義的符號組合到一起來描述字元或者字串的方法,或者說正則就是用來描述一類事物的規則.它內嵌在python中,並通過re模組來實現,Regex模式被編譯成一系列的位元組碼,然後由C編寫的匹配引擎執行.re模組的作用是對字串進行過濾,在一字串中如果想要找到想要得到的內容就需要告知其過濾規則,這個過濾規則就是Regex.
常用匹配模式:
import re# 待處理字串str1 = ‘abc-d$eaf+ \n 1*/__g12a3‘# findall()在字串中尋找所有滿足條件的# \w尋找字母數字底線 \W尋找非字母數字底線print(re.findall(‘\w‘,str1))print(re.findall(‘\W‘,str1))# \s尋找所有不可見字元 \S尋找所有可見字元print(re.findall(‘\s‘,str1))print(re.findall(‘\S‘,str1))# \d尋找任一數字 \D尋找任意非數字print(re.findall(‘\d‘,str1))print(re.findall(‘\D‘,str1))# \nprint(re.findall(‘\n‘,str1))# .匹配除了分行符號的任一字元print(re.findall(‘.‘,str1))# \s\w\d 都是匹配單個字元# 匹配重複字元* + ? {}# *前面的運算式匹配0次或多次print(re.findall(‘\w\d*‘,str1))# +前面的運算式匹配1次或多次print(re.findall(‘\d+‘,‘1 11 asf 2‘))# ?前面的運算式匹配1次或0次print(re.findall(‘\d?‘,‘1 111‘))# {m,n}最少m次,最多n次print(re.findall(‘\d{1,3}‘,‘1 12111‘))#{m}必須是m次print(re.findall(‘[a-z]{3}‘,‘aaa aa a aa aaa aaaa‘))# 從字元中找到左右的0或1或2# | 匹配範圍print(re.findall(‘0|1|2‘,‘123af45ad60d21‘))# []字元集合 中括弧中的符號不是整體是單個字元print(re.findall(‘[012]‘,‘123af45ad60d21‘))# 在範圍匹配時使用脫字元表示取反print(re.findall(‘[^0-9]‘,‘123af45ad60d21‘))# 請找出所有的數字0-9和字母a-z A-Z 注意 減號只有在兩個字元中間才有範圍的意思print(re.findall(‘[0-9a-zA-Z]‘,‘123+_lk#$a‘))# ^ 匹配行首print(re.findall(‘^h‘,‘hellohh‘))# $ 匹配行尾 注意$寫在運算式的後面print(re.findall(‘ha$‘,‘hellohha‘))# \b匹配單詞末尾print(re.findall(r‘h\B‘,‘elloh wohrld okhi‘))# 貪婪匹配 * +# 會一直匹配到不滿足條件為止 用問好來阻止貪婪匹配(匹配最少滿足條件的字元數)print(re.findall(‘\w*?‘,‘sfasdefd‘))src = "<img src=‘www.baidu.jpg‘><img src=‘www.baidu1.jpg‘><img src=‘www.baidu2.jpg‘>"# ()用於給Regex分組(group) 不會改變原來的運算式邏輯意義# 優先取出括弧內的內容 ?:取消括弧的優先順序print(re.findall("src=‘(.+?)‘",src))二.subprocess模組
subprocess模組是python2.4中新增的一個模組,它允許你產生新的進程,串連到它們的in/out/err管道,並擷取他們的返回碼.
subprocess模組中常用函數:
subprocess.run() Python 3.5中新增的函數。執行指定的命令,等待命令執行完成後返回一個包含執行結果的CompletedProcess類的執行個體
subprocess.call() 執行指定的命令,返回命令執行狀態,其功能類似於os.system(cmd)。
subprocess.Popen() 該類用於在一個新的程式中執行一個子程式.上面的函數都是基於subprocess.Popen類實現的
執行個體代碼:
import subprocessres = subprocess.run(‘tasklist‘,shell=True,stdout=subprocess.PIPE)print(res.stdout.decode(‘gbk‘))print(res.stderr)#res = subprocess.call(‘tasklist‘,shell=True)print(res)# 第一個進程a讀取tasklist的內容 將資料交給另一個進程b 另一個進程b將資料寫到檔案中res1 = subprocess.Popen(‘tasklist‘,stdout=subprocess.PIPE,shell=True,stderr=subprocess.PIPE)res2 = subprocess.Popen(‘findstr cmd‘,stdout=subprocess.PIPE,shell=True,stderr=subprocess.PIPE,stdin=res1.stdout)print(res2.stdout.read().decode(‘gbk‘))
Python常用模組(四)