繁体   English   中英

给定一个for循环中的IF-ELSE语句,我只能在满足条件一次时才跳过IF吗? 蟒蛇

[英]Given an IF-ELSE statement inside a for loop, can I only skip the IF when the condition is met once? python

下面是通过在动词的末尾添加“ X”来标记句子中的动词的功能。 这是使用spaCy进行POS标记完成的。 该函数在for循环中具有if-else语句(请参见下文)。 if语句检查单词是否是要标记的动词。

但是,我希望能够在找到n个动词后跳过IF部分,然后仅继续使用该函数的其余部分运行。 我知道这可能是一个简单或愚蠢的问题,尝试了while循环并continue但无法正常工作。 有没有办法做到这一点?

def marking(row):
    chunks = []
    for token in nlp(row):
        if token.tag_ == 'VB': 
        # I would like to specify the n number of VB's to be found
        # once this is met, only run the else part
            chunks.append(token.text + 'X' + token.whitespace_)
        else:
            chunks.append(token.text_with_ws)
    L = "".join(chunks)
    return L

添加计数器和break

def marking(row, max_verbs=5):
    chunks = []
    verbs = 0
    for token in nlp(row):
        if token.tag_ == 'VB':
            if verbs >= max_verbs:
                break  # Don't add anymore, end the loop
            chunks.append(token.text + 'X' + token.whitespace_)
            verbs += 1
        else:
            chunks.append(token.text_with_ws)
    return "".join(chunks)

通过marking(row, max_verbs=N)调用它marking(row, max_verbs=N)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM