Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用正则表达式计算每个字符串的出现次数_Python 3.x_Regex_Re - Fatal编程技术网

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

Python 3.x 使用正则表达式计算每个字符串的出现次数,python-3.x,regex,re,Python 3.x,Regex,Re,给定这样的模式 pattern = re.compile(r'\b(A|B|C)\b') 和一个巨大的\u字符串我想用一个字符串D替换与模式匹配的每个子字符串,并找到每个字符串a、B和C的出现次数。最可行的方法是什么 一种方法是将每个字符串的模式拆分为3个模式,然后使用subn pattern_a = re.compile(r'\bA\b') pattern_b = re.compile(r'\bB\b') pattern_c = re.compile(r'\bC\b') huge_strin

给定这样的模式

pattern = re.compile(r'\b(A|B|C)\b')
和一个
巨大的\u字符串
我想用一个字符串
D
替换与模式匹配的每个子字符串,并找到每个字符串
a
B
C
的出现次数。最可行的方法是什么

一种方法是将每个字符串的模式拆分为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次穿过巨大的_字符串。有更好的方法吗?

你可以在两次传球中完成,第一次只是计数,然后第二次做替补。这意味着如果你的搜索空间像a | b | c | d | e等那样增长,你仍然只会做两次传球,你的传球次数将不会基于你可能的比赛次数

重新导入
从收款进口柜台
string=“a j h s j a b c”
pattern=re.compile(r'\b(a | b | c)\b')
计数=计数器(pattern.findall(字符串))
string\u update=pattern.sub('d',string)
打印(计数、字符串、字符串更新、sep=“\n”)
输出

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

您可以将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")
请参阅,输出

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