在学习Python过程,对于分组与findall不太理解,所以归纳总结了一下,以下为本人python学习总结的一部分:

2.1 findall

查询到字符串,则返回全部字符的列表,否则返回空列表,参数与match一样

import re
pattern = r'itcast'
s = 'Itcaste,itcast1,itcast'
match = re.findall(pattern,s,re.I)
print(match)

 

2.2 Findall与分组

findall如果使用了分组,则输出的内容将是分组中的内容而非find到的结果,为了得到find到的结果,要加上问号来启用“不捕捉模式”

不启用分组:使用 \|

import re
match = re.findall("(1\d+\|[a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)

#输出:['1234|asss', '1345|adda']

 

不启用分组:使用 |

import re
match = re.findall("(1\d+|[a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)

#输出:['1234', 'asss', '1345', 'adda']

 

 

启用分组:使用 \|

import re
match = re.findall("(1\d+)\|([a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)

[('1234', 'asss'), ('1345', 'adda')]

 

启用分组:使用 |

 

import re
match = re.findall("(1\d+)|([a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)

#  输出:[('1234', ''), ('', 'asss'), ('1345', ''), ('', 'adda')]

#    (1\d+)匹配到了,生成一个元组,([a-z]+)匹配到了生成一个元组,然后findall继续查找

#    元组中只有一个元素,那那么在后面需要添加一个dot逗号

 

  findall如果使用了分组,则输出的内容将是分组中的内容将匹配规则结果自动生成一个元组,最后的结果组合成一个列表)而非find到的结果,为了得到find到的结果,要加上问号来启用“不捕捉模式”

import re
match = re.findall("(?:1\d+)|(?:[a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)

['1234', 'asss', '1345', 'adda']

结果与:match = re.findall("(1\d+|[a-z]+)","1234|asss|ZZZ|1345|adda") 一样

 

findall+分组模式,可以与字典dict函数配合使用,将结果转为字典

import re
match = re.findall("(1\d+)\|([a-z]+)","1234|asss|ZZZ|1345|adda")
print(match)
dict1 = dict(match)
print(dict1)
#以下为程序结果:

[('1234', 'asss'), ('1345', 'adda')]
{'1345': 'adda', '1234': 'asss'}

 

2.3一个利用findall的爬虫实例

 

import requests
import re
respose=requests.get('http://www.xbiquge.la/10/10489/').content.decode('utf-8')
title_list=re.findall('html\'\s>([\u4e00-\u9fa5]{1,4}\d{0,5}[\u4e00-\u9fa5]?\s[\u4e00-\u9fa5]{1,20})', respose)
print(title_list)

上述实例使用正则表达式的findall方法结合分组使用,直接将分组的内容返回一个列表,这个列表一般用于后续使用,可使用for循环打印

 

posted on 2020-12-13 11:59  Howell_Duan  阅读(816)  评论(0编辑  收藏  举报