如何在同一个Python函数中匹配更多的带有可选参数的regex选项?

问题描述 投票:0回答:1

我有一个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))

它的作用是对同一文本中所有的regex匹配项进行求和。然而。opzione2opzione3 是可选的,我可以有更多的可能性,包括更多的regex或不。然而,这段代码并不工作。

它被称为像。

一个选项

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
1个回答
0
投票

你的逻辑是错误的。

if opzione2 != None and opzione3 == None:
    # we get here only if opzione3 is None…
    matches_prima2 = re.findall(opzione2, x)
    lunghezza2 = len(matches_prima2)
    # …so there is no way opzione3 is not None HERE:
    if opzione2 != None and opzione3 != None:
        matches_prima3 = re.findall(opzione3, x)

你可能想要这样的东西:

def find_regex(regex, text, opzione2= None, opzione3 = None):
    lista = []
    for x in text:
        matches_prima = re.findall(regex, x)
        matches_prima2 = []
        matches_prima3 = []
        if opzione2 is not None:
            matches_prima2 = re.findall(opzione2, x)
            if opzione3 is not None:
                matches_prima3 = re.findall(opzione3, x)
        lunghezza = len(matches_prima) + len(matches_prima2) + len(matches_prima3)
        lista.append(lunghezza)
    print("The number of {} matches is ".format(regex), sum(lista))
© www.soinside.com 2019 - 2024. All rights reserved.