python正規表現re findallは一致する文字列を返します

1917 ワード

python正規表現re findallメソッドは、一致するサブ列をリスト形式で返すことができる.
re.findall(pattern, string[, flags]):
stringを検索し、一致するすべてのサブ列をリスト形式で返します.まず簡単なコードを見てみましょう:import re p=re.compile(r'd+')print p.findall('one 1 two 2 three 3 four 4')###output###['1','2','3','4']は少し複雑です例えばinfo='baidu'私たちのニーズは正規表現でウェブサイトとアンカーテキストを抽出することです.それはfindall()
import re
relink = ' (.*) '
info = ' baidu '
cinfo = re.findall(relink,info)
print cinfo
出力の結果:[('http://www.baidu.com','baidu')]は、一致した結果によって形成されるメタグループ形式のリストを返します.正則で置き換える必要がある場合はpython re subを見てください
 
 
以下はreを用いたウェブサイトの地図爬虫類です.findall構文
import urllib2
import re
def download(url,user_agent='wswp', num_retries=2):
print 'downloading:',url
headers={'User-agent':user_agent}
request=urllib2.Request(url,headers=headers)
try:
html=urllib2.urlopen(url).read()
except urllib2.URLError as e:
print 'download error:', e.reason
html=None
if num_retries>0:
if hasattr(e, 'code') and 500<=e.code<600:
#recursively retry 5XX http errors
return download(url, user_agent,num_retries-1)
return html

def crawl_sitemap(url):
#download the sitemap file
sitemap=download(url)
#extract the sitemap links
links = re.findall('(.*?)',sitemap)
#download each link
for link in links:
html=download(link)

 
転載先:https://www.cnblogs.com/mrruning/p/7637463.html