Home > other >  Finding next element with while loop python
Finding next element with while loop python

Time:09-28

im stuck with this idea. Id like to print the verb that come just right after the noun of pronoun so i'm iterating , until the loop find a verb. then print it. But it seems to print me not just verbs but also other elements. Any idea were i could go wrong ? thank you so much

 points = [('I', 'PRON', 'nsubj'),
         ('don', 'AUX', 'aux'),
         ('t', 'PART', 'neg'),
         ('hope', 'VERB', 'ROOT'),
         ('that', 'SCONJ', 'mark'),
         ('the', 'DET', 'det'),
         ('salary', 'NOUN', 'nsubj'),
         ('will', 'AUX', 'aux'),
         ('change', 'VERB', 'ccomp'),
         ('.', 'PUNCT', 'punct')]

for i, (word, pos, dep) in enumerate(points):
    intermediate_list_sentences = []

    if pos == "PRON" or pos == "NOUN":
        iterate = 1
        while points[i iterate][1] != "VERB":
            iterate =1
            print(points[i iterate][0])

OUTPOUT DESIRED => HOPE

CodePudding user response:

To fix your code, you just have to print the word after you skipped all the non-verb words, not the non-verb words themselves, i.e. move the print out of the loop:

while points[i iterate][1] != "VERB":
    iterate =1
print(points[i iterate][0])

Alternatively, you could create an iter from the list of words and use two nested for loops iterating that same iterator:

it = iter(points)
for word, pos, dep in it:
    if pos in ("PRON", "NOUN"):
        print(word)
        for word2, pos2, _ in it:
            if pos2 == "VERB":
               print(word2)
               break

Or more concise, using next to get the matching VERB:

it = iter(points)
for word, pos, dep in it:
    if pos in ("PRON", "NOUN"):
        verb = next((word2 for word2, pos2, _ in it if pos2 == "VERB"), None)
        print(word, verb)

Output:

I hope
salary change
  • Related