我有一个包含句子的 txt 文件,并且能够从其中的列表中查找单词。我想将“找到的行”上方的行打印到单独的列表中。我用下面的代码尝试了它,但这只返回 []
。
这是我的代码:
fname_in = "test.txt"
lv_pos = []
search_list = ['word1', 'word2']
with open (fname_in, 'r') as f:
file_l1 = [line.split('\n') for line in f.readlines()]
counter = 0
for word in search_list:
if word in file_l1:
l_pos.append(file_l1[counter - 1])
counter += 1
print(l_pos)
文本文件看起来像这样:
Bla bla bla
I want this line1.
I found this line with word1.
Bla bla bla
I want this line2.
I found this line with word2.
我想要的结果是这样的:
l_pos = ['I want this line1.','I want this line2.']
最佳答案
在示例的第二行中,您编写了 lv_pos
而不是 l_pos
。在 with
语句中,我认为您可以这样修复它:
fname_in = "test.txt"
l_pos = []
search_list = ['word1', 'word2']
file_l1 = f.readlines()
for line in range(len(file_l1)):
for word in search_words:
if word in file_l1[line].split(" "):
l_pos.append(file_l1[line - 1])
print(l_pos)
我对这个解决方案并不感到兴奋,但我认为它可以通过最少的修改修复您的代码。
关于python - 是否可以通过列表中的单词搜索 txt 文件并返回上面的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244718/