3 回答
TA贡献1820条经验 获得超2个赞
该变量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])
TA贡献1998条经验 获得超6个赞
您无权访问列表推导式/生成器表达式等之外的变量。该错误是有效的,因为当您尝试附加它时未定义“单词”。
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)
TA贡献1815条经验 获得超13个赞
避免在一行上写 for 循环:它会降低可读性并可能导致问题。
试试这个:
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)
添加回答
举报