Php 在Python中实现preg_match_all
我基本上希望以Python的方式从PHP获得与preg\u match\u all()相同的功能 如果我有一个正则表达式模式和一个字符串,有没有一种方法可以搜索该字符串并返回一个元音出现的字典,以及它在字符串中的位置 例如:Php 在Python中实现preg_match_all,php,python,regex,Php,Python,Regex,我基本上希望以Python的方式从PHP获得与preg\u match\u all()相同的功能 如果我有一个正则表达式模式和一个字符串,有没有一种方法可以搜索该字符串并返回一个元音出现的字典,以及它在字符串中的位置 例如: s = "supercalifragilisticexpialidocious" 将返回: { 'u' : 1, 'e' : 3, 'a' : 6, 'i' : 8, 'a' : 11, 'i' : 13, 'i' : 15 } 比如说: i
s = "supercalifragilisticexpialidocious"
将返回:
{
'u' : 1,
'e' : 3,
'a' : 6,
'i' : 8,
'a' : 11,
'i' : 13,
'i' : 15
}
比如说:
import re
def findall(pattern, string):
res = {}
for match in re.finditer(pattern, string):
res[match.group(0)] = match.start()
return res
print findall("[aeiou]", "Test this thang")
请注意,re.finditer
仅查找不重叠的匹配项。并且dict键将被覆盖,因此,如果要进行第一次匹配,必须将最里面的循环替换为:
for match in re.finditer(pattern, string):
if match.group(0) not in res: # <-- don't overwrite key
res[match.group(0)] = match.start()
对于re.finditer中的匹配(模式、字符串):
如果match.group(0)不在res:#中,您请求的不能是字典,因为它有多个相同的键。但是,您可以将其放入元组列表中,如下所示:
>>> [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
[('u', 1), ('e', 3), ('a', 6), ('i', 8), ('a', 11), ('i', 13), ('i', 15), ('i', 18), ('e', 20), ('i', 23), ('a', 24), ('i', 26), ('o', 28), ('i', 30), ('o', 31), ('u', 32)]
没有regexp,您可以更快地完成此操作
[(x,i) for i,x in enumerate(s) if x in "aeiou"]
以下是一些时间安排:对于
s=“supercalifragilisticexpialidocious”
对于s=“supercalifragilisticexpialidocious”*100
timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
100 loops, best of 3: 2.01 ms per loop
timeit [(x,i) for i,x in enumerate(s) if x in "aeiou"]
1000 loops, best of 3: 1.24 ms per loop
timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
100 loops, best of 3: 2.01 ms per loop
timeit [(x,i) for i,x in enumerate(s) if x in "aeiou"]
1000 loops, best of 3: 1.24 ms per loop