【发布时间】:2021-04-01 20:33:33
【问题描述】:
我被要求找出给定字符串中出现的子字符串(不区分大小写,带/不带标点符号)的总数。 一些例子:
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。我错过了什么吗?有没有更好(性能优化)的方法来做到这一点?
【问题讨论】:
-
你需要什么额外的匹配?只有不区分大小写?
-
我已经有了所有的匹配,问题是知道是否有更好的方法来做到这一点。因为这可以使执行时间达到预期的 0.25 秒
-
Regex 通常比人们需要的要多得多。如果您只为不区分大小写的匹配选择正则表达式,
text.lower().count(word.lower())会快得多。你需要另一个正则表达式吗?或者,您可能会发现杂乱但更具体优化的代码。 -
看我上面的例子,它的混合(大小写,标点符号,括号)等。如果我选择
.count,假设txt = "texts texts texts',如果我搜索text,计数将返回3,我不想要那个(它只需要返回一个完全匹配的单词) -
是的,当然,就我的目标表现而言..
标签: python regex string performance