gpt4 book ai didi

php - 在 Python 中实现 preg_match_all

转载 作者:行者123 更新时间:2023-11-28 19:51:51 25 4
gpt4 key购买 nike

我基本上希望以 Python 的方式从 PHP 获得与 preg_match_all() 相同的功能。

如果我有一个正则表达式模式和一个字符串,有没有一种方法可以搜索该字符串并取回每个出现的元音及其在字符串中的位置的字典?

例子:

s = "supercalifragilisticexpialidocious"

会返回:

{
'u' : 1,
'e' : 3,
'a' : 6,
'i' : 8,
'a' : 11,
'i' : 13,
'i' : 15
}

最佳答案

不用正则表达式你可以更快做这件事

[(x,i) for i,x in enumerate(s) if x in "aeiou"]

以下是一些时间安排:
对于 s = "supercalifragilisticexpialidocious"

timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
10000 loops, best of 3: 27.5 µs per loop

timeit [(x,i) for i,x in enumerate(s) if x in "aeiou"]
100000 loops, best of 3: 14.4 µs per loop

对于 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

关于php - 在 Python 中实现 preg_match_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com