首页 > 解决方案 > Python - 如何始终将文档中找到的列表中的单词打印到另一个列表?

问题描述

我想要一个包含整行的列表和一个包含单词的列表,以便稍后将其导出到 Excel。

我的代码总是返回:

NameError: name 'word' is not defined

这是我的代码:

l_lv = []
l_words = []

fname_in = "test.txt"
fname_out = "Ergebnisse.txt"


search_list =['kostenlos', 'bauseits', 'ohne Vergütung']

with open(fname_in,'r') as f_in:
    for line in f_in:
        if any (word in line for word in search_list):
            l_lv.append(line)
            l_words.append(word)


print(l_lv)
print(l_words)

编辑:我有一个包含文本的文件,它看起来像 fname_in 和我希望它被搜索的单词列表(search_list)。总是当在文件中找到单词时,我希望将单词写入列表 l_words 并将句子写入列表 l_lv。

这些行的代码有效。但它不会返回单词。

这里有一个例子:

fname_in ='sentance1 里面有 kostenlos。废话。另一个有 kostenlos 的句子。sentance3 里面有 bauseits。废话。另一个有 bauseits 的句子。blablabla。

结果,我希望拥有:

l_lv = ['sentance1 with kostenlos', 'another sentance2 with kostenlos','sentance3 with bauseits', 'another sentance4 with bauseits']

l_words = ['kostenlos', 'kostenlos', 'bauseits', 'bauseits']

标签: pythonlist

解决方案


您无权访问列表理解/生成器表达式等之外的变量。该错误是有效的,因为当您尝试附加它时未定义“单词”。

l_lv = []
l_words = []

fname_in = "test.txt"
fname_out = "Ergebnisse.txt"


search_list =['kostenlos', 'bauseits', 'ohne Vergütung']

with open(fname_in,'r') as f_in:
    for line in f_in:
        if any(word in line for word in search_list):
            l_lv.append(line)
            #for nested list instead of a flat list of words 
            #(to handle cases where more than 1 word matches in the same sentence.)
            #words_per_line = []
            for word in search_list:
                l_words.append(word)
                #words_per_line.append(word)
            #if words_per_line:
                #l_words.append(words_per_line)
print(l_lv)
print(l_words)

推荐阅读