python - 我如何从字符串中获取特定单词的下两个单词?

标签 python python-3.x string list loops

我有一个特定单词的列表

['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/

相关文章:

python - Numpy- 矩阵的权重和求和行

python - 反斜杠 b 在 Python 中有什么作用?

python - 如何获取Python/Pip包的PyPi链接、许可证、代码和主页?

python - 如果它包含 pandas 数据框中基于字典键的子字符串,则替换整个字符串

python - 为什么这些点在Python中不相等?

c++ - push_back 与 emplace_back 到 std::vector<std::string>

java - 当我们进行concat操作时,字符串将在java中哪里创建对象?

python - 在 python 中,如何从日期和时间创建时区感知日期时间?

python - 你能用turtle.write获取用户输入吗?

python - ValueError : Error when checking input: expected dense_151_input to have 3 dimensions, 但得到形状为 (2, 2100) 的数组