使用正则表达式计算每个字符串的出现次数



给定这样的模式

pattern = re.compile(r'b(A|B|C)b')

huge_string我想用字符串D替换与模式匹配的每个子字符串,并找到每个字符串ABC的出现次数。什么是最可行的方法?

一种方法是将每个字符串的模式拆分为 3 个模式,然后使用 subn

pattern_a = re.compile(r'bAb')
pattern_b = re.compile(r'bBb')
pattern_c = re.compile(r'bCb')
huge_string, no_a = re.subn(pattern_a, D, huge_string)
huge_string, no_b = re.subn(pattern_b, D, huge_string)
huge_string, no_c = re.subn(pattern_c, D, huge_string)

但它需要 3 次通过huge_string。有没有更好的方法?

您可以将可调用对象作为替换参数传递给re.sub,并在单次替换传递期间收集必要的计数详细信息:

import re
counter = {}
def repl(m):
if m.group() in counter:
counter[m.group()] += 1
else:
counter[m.group()] = 1
return 'd'
text = "a;b o a;c a l l e d;a;c a b"
rx = re.compile(r'b(a|b|c)b')
result = rx.sub(repl, text)
print(counter, result, sep="n")

在线查看 Python 演示,输出;

{'a': 5, 'b': 2, 'c': 2}
d;d o d;d d l l e d;d;d d d

你可以用 2 次传递来完成,第一次只是计数,然后第二次做 sub。 这意味着如果你的搜索空间像 a|b|c|d|e 等一样增长,你仍然只会做 2 次传递,你的传球次数不会基于你可能的匹配次数。

import re
from collections import Counter
string = " a j h s j a b c "
pattern = re.compile(r'b(a|b|c)b')
counts = Counter(pattern.findall(string))
string_update = pattern.sub('d', string)
print(counts, string, string_update, sep="n")

输出

Counter({'a': 2, 'b': 1, 'c': 1})
a j h s j a b c 
d j h s j d d d 

最新更新