接上篇文章杭棵,這篇文章說(shuō)說(shuō)在python中擂达,正則表達(dá)式的使用,python提供了re模塊來(lái)處理正則表達(dá)式
還是用天氣預(yù)報(bào)的接口
{"reason":"查詢成功!","result":{"city":"上海","realtime":{"temperature":"26","humidity":"94","info":"晴","wid":"00","direct":"北風(fēng)","power":"0級(jí)","aqi":"65"},"future":[{"date":"2019-09-10","temperature":"25\/32℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"南風(fēng)轉(zhuǎn)東南風(fēng)"},{"date":"2019-09-11","temperature":"25\/32℃","weather":"陰轉(zhuǎn)多云","wid":{"day":"02","night":"01"},"direct":"東北風(fēng)轉(zhuǎn)東南風(fēng)"},{"date":"2019-09-12","temperature":"25\/31℃","weather":"陰轉(zhuǎn)多云","wid":{"day":"02","night":"01"},"direct":"東風(fēng)轉(zhuǎn)東南風(fēng)"},{"date":"2019-09-13","temperature":"24\/31℃","weather":"多云","wid":{"day":"01","night":"01"},"direct":"東南風(fēng)轉(zhuǎn)東風(fēng)"},{"date":"2019-09-14","temperature":"24\/29℃","weather":"小雨轉(zhuǎn)多云","wid":{"day":"07","night":"01"},"direct":"東北風(fēng)"}]},"error_code":0}
實(shí)例一:使用re.sub(pattern, repl, string, count=0, flags=0) 函數(shù)胳泉,將字符串的?‘reason’替換成‘start’
參數(shù)講解:
pattern :正則表達(dá)式
repl:需要替換的字符串八回,或者函數(shù)名,這里是可以自定義函數(shù)的
string :需要處理的字符串
count:需要替換的個(gè)數(shù)吩坝,0表示替換所有
比如:re.sub('reason','start',text,0)毒姨,表示匹配text中所有符合‘reason’表達(dá)式的地方,并將其替換成‘start’
結(jié)果:
實(shí)例二:分別使用search()钉寝,match()弧呐,findall()方法查詢接口中的日期信息
三個(gè)函數(shù)解釋:
re.search(pattern, string, flags=0)
匹配整個(gè)字符串,找到一個(gè)合適的即停止
re.match(pattern, string, flags=0)match
從字符串開(kāi)頭匹配嵌纲,如果開(kāi)頭沒(méi)有匹配到俘枫,則返回None
re.findall(pattern, string, flags=0)findall
匹配整個(gè)字符串,并返回所有匹配結(jié)果
參數(shù)講解:
pattern :正則表達(dá)式
string :需要處理的字符串
結(jié)果:
實(shí)例三: 只獲取日期逮走,不要date鸠蚪,例如:2019-09-10
方法一:
r=re.search('"date":"(.{10})"',text)
r.group(1)
group()函數(shù)是用來(lái)取search()函數(shù)和match()函數(shù)中match的值,可以看實(shí)例二的結(jié)果师溅,search和findall返回結(jié)果格式是不同的
正則表達(dá)式中()代表一組字符的意思,group()函數(shù)中可以傳遞一個(gè)參數(shù)茅信,這個(gè)參數(shù)就是第幾組數(shù)據(jù),0是返回所有险胰,1是返回第一組數(shù)據(jù)汹押,所以返回結(jié)果是:2019-09-10
方法二:
r = re.findall('"date":"(.{10})"',text)
這個(gè)方法會(huì)返回所有符合要求的日期