python 正則表示式 之re.findall
阿新 • • 發佈:2019-01-23
python 正則表示式 re findall 方法能夠以列表的形式返回能匹配的子串。
re.findall(pattern, string[, flags]):
搜尋string,以列表形式返回全部能匹配的子串。先看個簡單的程式碼:
import re
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
### output ###
# ['1', '2', '3', '4']
稍微複雜點比如:
info = '<a href="http://www.baidu.com">baidu</a>' 我們的需求是通過正則表示式提取網址和錨文字,那可以用到
findall()
relink = '<a href="(.*)">(.*)</a>'
info = '<a href="http://www.baidu.com">baidu</a>'
cinfo = re.findall(relink,info)
print cinfo
輸出的結果:[('http://www.baidu.com', 'baidu')] 返回的是一個列表,列表裡面是匹配的結果形成的元組形式
例子function:
def get_yizhe_info(url): # url weiyigecanshu #url='http://book.douban.com/subject/6082808/?from=tag_all' # For Test req = urllib2.Request(url, headers=hds2[np.random.randint(0,len(hds2))]) html = urllib2.urlopen(req).read() html = html.replace('\n', '') #print html try: reg_temp='<span class="pl"> 譯者</span>: *?(.*?)<br/>' temp=re.findall(reg_temp,html) print temp if temp: reg_author = '<a class="" href=".*?">(.*?)</a>' name = re.findall(reg_author, temp[0]) print name str='' for na in name: str=na+'/'+str str = str.replace(str,str[:-1]) except: str = '暫無' return str