我有一个特定单词的列表
['to', 'with', 'in', 'for']
我想创建一个函数,它接受一个句子,如果我的列表中有一个单词,它应该选择它后面的接下来的两个单词并将它们加入到列表中(我的句子的一部分需要它发电机)。例如:
sentence = 'In the morning I went to the store and then to the restaurant'
我想要得到
['tothe', 'tostore', 'tothe', 'torestaurant']
我写了这段代码:
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
但是我得到了这个:
['tothe', 'tostore', 'tothe', 'tostore']
而不是这个:
['tothe', 'tostore', 'tothe', 'torestaurant']
最佳答案
这应该可以给你你想要的东西。请注意,您可以使用 Python 中的“in”运算符来检查该单词是否存在于字符串列表中,在这种情况下无需循环列表。另外如上所述,这里使用 .index 是不够的,您可以使用 enumerate 来获取索引以及列表中的项目。
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
关于python - 我如何从字符串中获取特定单词的下两个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510536/