user9440895
user9440895

Reputation:

how could i get two next words of specific word from string?

I have a list of specific words

['to', 'with', 'in', 'for']

I want to make a function, which takes a sentence and if there is a word form my list, it should select the next two words after it and put them joined to the list(i need it for a part of my sentence generator). For example:

sentence = 'In the morning I went to the store and then to the restaurant'

I want to get

['tothe', 'tostore', 'tothe', 'torestaurant']

I wrote this code:

preps = ['to', 'with', 'in', 'for']
def nextofnext_words_ofnegs(sentence):
    list_of_words = sentence.split()
    next_word = []
    for i in list_of_words:
        for j in preps:
            if i == j:
                next_word.append(j + list_of_words[list_of_words.index(i) + 1])
                next_word.append(j + list_of_words[list_of_words.index(i) + 2])
    return next_word

However i get this:

['tothe', 'tostore', 'tothe', 'tostore']

Instead of this:

['tothe', 'tostore', 'tothe', 'torestaurant']

Upvotes: 2

Views: 847

Answers (1)

hysoftwareeng
hysoftwareeng

Reputation: 497

This should work to give you what you want. Note that you can use the "in" operator in Python to check if the word exists in your string list, there is no need to loop the list here in this case. Also as mentioned above, using of .index is insufficient here, you can use enumerate to get the index as well as the item in the list.

preps = ['to', 'with', 'in', 'for']
def nextofnext_words_ofnegs(sentence):
    list_of_words = sentence.split()
    next_word = []
    for idx, word in enumerate(list_of_words):
        if word in preps:
            next_word.append(word + list_of_words[idx + 1])
            next_word.append(word + list_of_words[idx + 2])
    return next_word

Upvotes: 3

Related Questions