我有一个带有句子的 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.']
jeck猫
森林海
饮歌长啸
相关分类