vendredi 14 juin 2019

How to tell python to continue evaluating after finding a result

I have a dictionary of words and a text. I would like to create a list that contains all the words contained in both the dictionary and the text, with the caveat that if a word in the dictionary exists more than once in the text, it should also append it to the list. so the list may continue a same word more than once, if that word repeats in the text.

I am using an if statement inside a for loop that stops iterating once a match is found and it goes to the next word in the dictionary without continuing to search for the first word again until the end of the text. the text is one string. Here is my code

text = 'The Notes will be a further issuance of and will form a single
 series with billion aggregate principal amount Notes due, in the case of the Notes, 
the principal amount of the Notes'
dictionary = ['Notes', 'issuance', 'form', 'series', 'aggregate', 'due', 
'case', 'constitution', 'executive']

list_of_words=[]
for word in (dictionary):
    if word in text:
        list_of_words.append(word)

What I would like to see is, for example, the word "Notes" repeat in the list_of_words because it exists in the dictionary and repeats in the text. As in the example below:

['Notes', 'issuance', 'form', 'series', 'aggregate', 'Notes, 'due', 'case', 'Notes']

However my code returns only the first instance of the match, as below:

['Notes', 'issuance', 'form', 'series', 'aggregate', 'due', 'case']

Aucun commentaire:

Enregistrer un commentaire