【发布时间】:2020-05-03 16:11:17
【问题描述】:
我有这个 Python 函数:
def find_regex(regex, text, opzione2= None, opzione3 = None):
lista = []
for x in text:
matches_prima = re.findall(regex, x)
lunghezza1 = len(matches_prima)
if opzione2 != None and opzione3 == None:
matches_prima2 = re.findall(opzione2, x)
lunghezza2 = len(matches_prima2)
if opzione2 != None and opzione3 != None:
matches_prima3 = re.findall(opzione3, x)
lunghezza3 = len(matches_prima3)
lunghezza = len(matches_prima) + len(matches_prima2) + len(matches_prima3)
lista.append(lunghezza)
print("The number of {} matches is ".format(regex), sum(lista))
它应该对同一文本中的所有正则表达式匹配进行总和。但是,opzione2 和 opzione3 是可选的,我可以有更多的可能性并包含更多的正则表达式。但是,此代码不起作用。
它被称为:
一个选项
FIND_FASE12T = re.compile(r"\]\s1\s([\w\s]+)\s2\sT")
find_regex(FIND_FASE12T, testo_fasi)
更多选项
FIND_FASE_PRIMA_123FRECCIAT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*→\s*T")
FIND_FASE_PRIMA_1FRECCIA23T = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*(T|3\sT)")
FIND_FASE_PRIMA_FRECCIA1F2FT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*→\s*(T|3\sT)")
find_regex(FIND_FASE_PRIMA_1FRECCIA23T, testo_fasi, FIND_FASE_PRIMA_123FRECCIAT, FIND_FASE_PRIMA_FRECCIA1F2FT)
我做错了什么?
【问题讨论】:
标签: python regex python-3.x function