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,并将sentance写入列表l_lv。

行的代码有效。但它并没有回话。

这里有一个例子:

fname_in="里面有kostenlos的忏悔1。另一个哨兵2和科斯滕洛斯在里面。哨兵3和鲍塞茨在里面。布拉布拉。又是一个哨兵,里面有包

因此,我希望拥有:

l_lv=[‘含有kostenlos的戊烷1’,‘含有kotenlos的另一个sentance2’,‘具有bauseits的戊烷3’,‘包含bauseits’的另一种sentance4’]

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

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

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)

变量word仅绑定在传递给any()的生成器表达式中,因此当您稍后尝试将其添加到列表中时,它不存在。似乎你不仅想知道搜索列表中的单词是否出现在行中,还想知道是哪个单词。试试这个:

for line in f_in:
found = [word for word in search_list if word in line]
if found:
l_lv.append(line)
l_words.append(found)

请注意,此代码假设每行中可以出现多个单词,并为每行在l_lv后面添加一个单词列表,这意味着l_lv是一个列表列表。如果您只想在每行中添加第一个单词:

l_words.append(found[0])

避免在一行中编写循环:这会降低可读性,并可能导致问题。

试试这个:

l_lv = []
l_words = []
input_file = "test.txt"
output_file = "Ergebnisse.txt"

search_list =['kostenlos', 'bauseits', 'ohne Vergütung']
with open(input_file,'r') as f:
for line in f:
for word in search_list:
if word in line:
l_lv.append(line)
l_words.append(word)

最新更新