计算Python正则表达式中捕获的命名组数和命名组总数
我有两张单子。一个列表计算Python正则表达式中捕获的命名组数和命名组总数,python,regex,Python,Regex,我有两张单子。一个列表ref,包含允许越来越大的灵活性的正则表达式项,另一个列表input,包含要与正则表达式匹配的输入列表。 到目前为止,我能够创建下面的匹配字典。下面是我试图创建的字典,match\u upd匹配由输入的键组成,值对应的匹配项来自ref。值项由ref中每个匹配元组项的第二项组成。此外,match中的每个值都包含实现匹配的命名捕获组。所需的输出,match_upd,将包含相同的值,但这些值中的每个值还将包括匹配的捕获组中成功匹配的命名捕获组的数量的计数,以及匹配的捕获组中匹配的
ref
,包含允许越来越大的灵活性的正则表达式项,另一个列表input
,包含要与正则表达式匹配的输入列表。
到目前为止,我能够创建下面的匹配
字典。下面是我试图创建的字典,match\u upd
<代码>匹配由输入的键组成,值对应的匹配项来自ref
。值项由ref
中每个匹配元组项的第二项组成。此外,match
中的每个值都包含实现匹配的命名捕获组。所需的输出,match_upd
,将包含相同的值,但这些值中的每个值还将包括匹配的捕获组中成功匹配的命名捕获组的数量的计数,以及匹配的捕获组中匹配的组的计数。
下面的例子非常抽象,如果让人感到困惑,我很抱歉。基本上,我试图统计一场比赛中可选捕获组的数量,也统计参与比赛的这些组的数量。我正在使用Python的新模块
我试图为match_upd
添加所需的输出,但没有取得任何成果:
def match(i,o,addr,ref,group,matchattributes,totalattributes):
m = regex.fullmatch(i[0],o[0])
if m:
addr.append(str(o).strip('('')').replace("'",""))
ref.append(i[1])
m = m.groupdict()
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is None:
group.append(k)
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is not None:
matchattributes.append(len(k))
for k,v in m.items():
if re.search(r'pd|pt|sd|st',k) is not None:
totalattributes.append(len(k))
我是编程新手,如果这个答案很简单,请原谅我。我基本上需要对语句的最后两个
进行计数。谢谢你的帮助和耐心。我知道了。回想起来,这是一个相当简单的解决方案。我只需要确定matchattributes
和totalattributes
变量的总计数。+=
函数就是解决方案,将总数追加到一个空列表中
def match(i,o,addr,ref,group,matchattributes,totalattributes):
matchcounter = 0
totalcounter = 0
m = regex.fullmatch(i[0],o[0])
if m:
addr.append(str(o).strip('('')').replace("'",""))
ref.append(i[1])
m = m.groupdict()
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is None:
group.append(k)
for k,v in m.items():
if v is not None and re.search(r'3(pd|pt|sd|st)',k):
matchcounter += 1
matchattributes.append(matchcounter)
for k,v in m.items():
if re.search(r'3(pd|pt|sd|st)',k):
totalcounter += 1
totalattributes.append(totalcounter)
你可以大大简化你的例子。使用短正则表达式和短输入字符串作为示例数据。
def match(i,o,addr,ref,group,matchattributes,totalattributes):
m = regex.fullmatch(i[0],o[0])
if m:
addr.append(str(o).strip('('')').replace("'",""))
ref.append(i[1])
m = m.groupdict()
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is None:
group.append(k)
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is not None:
matchattributes.append(len(k))
for k,v in m.items():
if re.search(r'pd|pt|sd|st',k) is not None:
totalattributes.append(len(k))
def match(i,o,addr,ref,group,matchattributes,totalattributes):
matchcounter = 0
totalcounter = 0
m = regex.fullmatch(i[0],o[0])
if m:
addr.append(str(o).strip('('')').replace("'",""))
ref.append(i[1])
m = m.groupdict()
for k,v in m.items():
if v is not None and re.search(r'pd|pt|sd|st',k) is None:
group.append(k)
for k,v in m.items():
if v is not None and re.search(r'3(pd|pt|sd|st)',k):
matchcounter += 1
matchattributes.append(matchcounter)
for k,v in m.items():
if re.search(r'3(pd|pt|sd|st)',k):
totalcounter += 1
totalattributes.append(totalcounter)