简体   繁体   中英

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

Below is a function that marks verbs in sentences by adding an 'X' at the end of the verb word. This is done using spaCy for POS tagging. The function has an if-else statement inside a for loop (see below). The if statement checks whether a word is a verb to be marked, or not.

However, I want to be able to skip the IF part once an n number of verbs has been found, and then only continue running with the rest of the function. I am aware this might be a simple or silly question and tried a while loop and continue but could not get this working. Is there a way to achieve this?

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

Add a counter and a 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)

Call it by marking(row, max_verbs=N)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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