1. 程式人生 > >python全棧開發 * 30知識點匯總 * 180713

python全棧開發 * 30知識點匯總 * 180713

html def 貪婪匹配 浮點數 起名字 基礎 sci imp 驗證

30  re模塊2
一.正則表達式在線測試 在線測試工具 http://tool.chinaz.com/regex/

(一).*?的用法:
. 是任意字符
* 是取 0 至 無限長度
? 是非貪婪模式。
合在一起就是 取盡量少的任意字符,一般不會這麽單獨寫,他大多用在:.*?x
就是取前面任意長度的字符,直到一個x出現
(二).問號"?"的四種用法
1.量詞,重復零次或一次
2.非貪婪匹配(惰性匹配)的象征( .*? )
3.?: 分組一開始加?:表示取消分組優先.
4.?p: 分組命名 html 標簽預言中用到.
二.re模塊常用方法
基礎查找
1.findall 分組優先級

ret=re.findall(r"(\d+\.?\d+)","123.546")
print(ret)
print(ret.remove(""))
#findall的優先級問題
ret=re.findall(‘www.(baidu|oldboy).com‘, ‘www.oldboy.com‘)
print(ret) #[‘oldboy‘] 這是因為findall會優先把匹配結果組裏內容返回,如果想要匹配結果,取消權限即可
ret=re.findall(‘www.(?:baidu|oldboy).com‘, ‘www.oldboy.com‘)
print(ret) #[‘www.oldboy.com‘] 註釋: 分組一開始加" ?: " 表示取消分組優先級.


2.search (group)
函數會在字符串內查找模式匹配,直到找到第一個匹配然後返回一個包含匹配信息的對象,該對象可以
通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。
ret=re.search("\d+","4huhi67377")
print(ret.group()) # 4
ret=re.search("\d+","4888huhi67377")
print(ret.group()) #4888
3.match (group)
ret=re.match("\d","4huhi67377") #match 裏的正則不管是什麽,默認在正則前加" ^ "

print(ret.group())
字符串處理
4.split 分組保留 優先級"正則" "(正則)"
ret=re.split("(\d+)","ghgh689jhhkjkj888hjh9777") # 用"\d+"切割字符串 加"(正則)"分組保留.
print(ret) #[‘ghgh‘, ‘689‘, ‘jhhkjkj‘, ‘888‘, ‘hjh‘, ‘9777‘, ‘‘]
ret=re.split("\d+","ghgh689jhhkjkj888hjh9777")
print(ret) #[‘ghgh‘, ‘jhhkjkj‘, ‘hjh‘, ‘‘]
5.sub 替換 ("正則","替換目標值","字符串",2)
ret=re.sub("\d+" ,"男神","alex1000wusir666")
print(ret) 結果 alex男神wusir男神
ret=re.sub("\d+" ,"男神","alex1000wusir666",1)
print(ret) 結果 alex男神wusir666

6.subn
ret=re.subn("\d+" ,"男神","alex1000wusir666")
print(ret) 結果 (‘alex男神wusir男神‘, 2)
代碼優化
7.compile
obj=re.compile("\d{4}")
ret=obj.search("676767hghjj787878gjggu")
print(ret.group()) #結果 6767
ret=obj.findall("hghjj787878gjggu")
print(ret.group()) 結果 6767
ret=obj.match("676767hghjj787878gjggu")
print(ret.group()) #6767
8.finditer 叠代功能
ret=re.finditer("\d+","ggjgu65565765hjhjk767")
for i in ret:
print(i.group()) #65565765 767
<二>
print(ret) # <callable_iterator object at 0x00000278077385C0>
print(next(ret).group()) # 65565765
print(next(ret).group()) # 767
三.綜合練習與擴展
1.匹配標簽
(1).普通版
ret = re.search("<\w+>\w+</\w+>","<h1>hello</h>")
print(ret.group()) # <h1>hello</h1>
(2).分組命名版
還可以在分組中利用?P<name>的形式給分組起名字,獲取的匹配結果可以直接用group(‘名字‘)拿到對應的值
ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
?P<tag_name> 起名字 ?P=tag_name 使用分組名字
print(ret.group("tag_name")) # h1
print(ret.group()) # <h1>hello</h1>
(3)分組索引 從1開始
如果不給組起名字,也可以用"\序號"來找到對應的組,表示要找的內容和前面的組內容一致
獲取的匹配結果可以直接用group(序號)拿到對應的值
ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
print(ret.group()) #<h1>hello</h1>
print(ret.group(1)) # h1
2.匹配整數和小數
ret=re.findall(r"-?\d+\.\d+|-?\d+","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) # [‘1‘, ‘-2‘, ‘60‘, ‘-40.35‘, ‘5‘, ‘-4‘, ‘3‘] 小數和整數都取
ret=re.findall(r"-?\d+\.\d+|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) # [‘1‘, ‘-2‘, ‘60‘, ‘‘, ‘5‘, ‘-4‘, ‘3‘] 只取整數
3.數字匹配
(1). 匹配一段文本中的每行的郵箱
http://blog.csdn.net/make164492212/article/details/51656638
正則表達式 : [\w:\./]{1,}
驗證: ret=re.findall("[\w:\./]{1,}","http://blog.csdn.net/make164492212/article/details/51656638")
print(ret) # [‘http://blog.csdn.net/make164492212/article/details/51656638‘]
(2).匹配一段文本中的每行的時間字符串,比如:‘1990-07-12’;^[1-9][0-9]{1,}\-[0-1][0-9]\-[0-3][0-9]
分別取出1年的12個月 # (^(0?[1-9]|1[0-2])$)
一個月的31天 # ^((0?[1-9])|((1|2)[0-9])|30|31)$
(3)匹配qq [1-9][0-9]{4,}
(4)浮點數 ^(-?\d+)(\.\d+)?$
四.flags有很多可選值
re.I(IGNORECASE)忽略大小寫,括號內是完整的寫法
re.M(MULTILINE)多行模式,改變^和$的行為
re.S(DOTALL)點可以匹配任意字符,包括換行符
re.L(LOCALE)做本地化識別的匹配,表示特殊字符集 \w, \W, \b, \B, \s, \S 依賴於當前環境,不推薦使用
re.U(UNICODE) 使用\w \W \s \S \d \D使用取決於unicode定義的字符屬性。在python3中默認使用該flag
re.X(VERBOSE)冗長模式,該模式下pattern字符串可以是多行的,忽略空白字符,並可以添加註釋
作業: 實現能計算類似
1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等類似公式的計算器程序
爬蟲練習:
import requests

import re
import json

def getPage(url):

response=requests.get(url)
return response.text

def parsePage(s):

com=re.compile(‘<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>‘
‘.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)評價</span>‘,re.S)

ret=com.finditer(s)
for i in ret:
yield {
"id":i.group("id"),
"title":i.group("title"),
"rating_num":i.group("rating_num"),
"comment_num":i.group("comment_num"),
}

def main(num):

url=‘https://movie.douban.com/top250?start=%s&filter=‘%num
response_html=getPage(url)
ret=parsePage(response_html)
print(ret)
f=open("move_info7","a",encoding="utf8")

for obj in ret:
print(obj)
data=json.dumps(obj,ensure_ascii=False)
f.write(data+"\n")

if __name__ == ‘__main__‘:
count=0
for i in range(10):
main(count)
count+=25

python全棧開發 * 30知識點匯總 * 180713