【问题标题】:Count number of occurences of each string using regex使用正则表达式计算每个字符串的出现次数
【发布时间】:2020-06-12 10:50:35
【问题描述】:

给定这样的模式

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

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

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

pattern_a = re.compile(r'\bA\b')
pattern_b = re.compile(r'\bB\b')
pattern_c = re.compile(r'\bC\b')
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。有没有更好的办法?

【问题讨论】:

    标签: python-3.x regex python-re


    【解决方案1】:

    您可以将 callable 作为替换参数传递给 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 demo online,输出;

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

    【讨论】:

      【解决方案2】:

      您可以分 2 次完成,第一次只是数数,然后第二次是次数。这意味着如果您的搜索空间增长为 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 
      

      【讨论】:

        猜你喜欢
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 2013-07-29
        • 2015-04-17
        • 2011-12-15
        • 2014-11-06
        • 1970-01-01
        • 2022-10-15
        相关资源
        最近更新 更多