gpt4 book ai didi

Python字符串出现次数正则表达式性能

转载 作者:行者123 更新时间:2023-12-03 14:37:23 26 4
gpt4 key购买 nike

我被要求找到给定字符串中出现的子字符串总数(不区分大小写,带/不带标点符号)。
一些例子:

count_occurrences("Text with", "This is an example text with more than +100 lines") # Should return 1
count_occurrences("'example text'", "This is an 'example text' with more than +100 lines") # Should return 1
count_occurrences("more than", "This is an example 'text' with (more than) +100 lines") # Should return 1
count_occurrences("clock", "its 3o'clock in the morning") # Should return 0
我选择了正则表达式而不是 .count()因为我需要完全匹配,最后得到:
def count_occurrences(word, text):
pattern = f"(?<![a-z])((?<!')|(?<='')){word}(?![a-z])((?!')|(?=''))"
return len(re.findall(pattern, text, re.IGNORECASE))
我得到了所有匹配的计数,但我的代码花了 0.10secs而预期时间是 0.025secs .我错过了什么吗?有没有更好的(性能优化的)方法来做到这一点?

最佳答案

好吧,我一直在努力让它在没有正则表达式的情况下工作,因为我们都知道正则表达式很慢。这是我想出的:

def count_occurrences(word, text):
spaces = [' ', '\n', '(', '«', '\u201d', '\u201c', ':', "''", "__"]
endings = spaces + ['?', '.', '!', ',', ')', '"', '»']
s = text.lower().split(word.lower())
l = len(s)
return sum((
(i == 0 and (s[0] == '' or any(s[i].endswith(t) for t in spaces)) and (s[1] == '' or any(s[i+1].startswith(t) for t in endings)))
or (i == l - 2 and any(s[i].endswith(t) for t in spaces) and (s[i+1] == '' or any(s[i+1].startswith(t) for t in endings)))
or (i != 0 and i != l - 2 and any(s[i].endswith(t) for t in spaces) and any(s[i+1].startswith(t) for t in endings))
) for i in range(l - 1))
整个文件 runs in ideone :
Ran 1 test in 0.025s

OK
这就是问题的要求。
逻辑很简单。让我们拆分 text来自 word , 都是小写的。现在让我们看看每对邻居。例如,如果索引 0 以有效定界符结束,而索引 1 以有效定界符开头,我们将其计为一次出现。让我们这样做直到 split 的最后几个。
由于性能在这里很重要,我们必须注意 spaces 的顺序。和 endings .我们基本上是在寻找满足条件的列表中的第一个。因此,首先找到更常见的变量很重要。例如,如果我声明:
spaces = ['(', '«', '\u201d', '\u201c', ':', "''", "__", '\n', ' ']
我得到的不是我的解决方案中的内容,而是 0.036秒。
例如,如果我声明一个数组:
spaces = [' ', '\n', '(', '«', '\u201d', '\u201c', ':', "''", "__", '?', '.', '!', ',', ')', '"', '»']
它具有所有分隔符并仅使用它,我得到 0.053 秒。这比我的解决方案多 60%。
以其他顺序声明分隔符可能有更好的解决方案。

关于Python字符串出现次数正则表达式性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65420550/

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