如何在 python 中打印精确术语后的单词

How to print words following an exact term in python

我需要在文本中打印 'ed' 之后的单词。但是,它不能正常工作 我认为表达式“following_word”有问题。 text.txt 文件包含文本:“Ed io timido e cheto ed inesperto,”你能帮帮我吗?

with open("text.txt", "r", encoding="utf8") as rf:
    text=list(rf)

y=["ed"]

for word in text:
    word_list=word.lower().split()
    for x in word_list:
        if x in y:
            following_word=word_list[word_list.index(y) +1]
            print(x+" "+following_word)

结果应该是:

ed io

不理解,

就像我在评论中写的那样,按“ed”拆分如下:

string = "Ed io timido e cheto ed inesperto"
for s in string.lower().split("ed "):
    if len(s):
        print(f"ed {s.split()[0]}")
  1. 要获得更简洁的解决方案,您可以使用标准 re(正则表达式)模块:
import re
search_terms = ["ed"]

for term in search_terms:
    following_words = re.findall(r"%s (\w+)" % term, string.lower())
    print('\n'.join(f'{term} {word}' for word in following_words))

输出:

ed io
ed inesperto
  1. 为了对您已有的内容进行绝对最小的更改,请使用枚举,并通过只查看每行末尾之前的一个来避免索引越界错误:
search_terms = ["ed"]

for words_line in text:
    word_list = words_line.lower().split()
    for i, word in enumerate(word_list[:-1]): # only look until the penultimate character
        if word in search_terms:
            following_word = word_list[i + 1]
            print(x + " " + following_word)

(相同的输出)