python - 是否可以通过列表中的单词搜索 txt 文件并返回上面的行?

标签 python list

我有一个包含句子的 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/

相关文章:

javascript - 使用 Javascript 或 Jquery 将复选框值获取到数组或列表

java - 如何区分同一个整数对象?

c++ - 如何删除 STD::List 中最近的 "Point"对象到某个 x,y?

python - 在 Django 管理对象页面中显示对象 ID(主键)

python - 支持嵌套类型中自定义类的默认序列化

python - 名称错误 : name 'BOTTOM' is not defined

java - 修改原始列表对象的问题?

python - 如何对这样的列表进行排序?

python - 基于 'similar' 浮点值合并 python 列表

python - 使用动态 CSV 命名将 For 循环导出到 CSV