繁体   English   中英

Python-如何始终将文档中找到的列表中的单词打印到另一个列表?

[英]Python - How do I print always the word from a list found in a document to another list?

我想要一个整行的列表和一个单词的列表,以便稍后将其导出到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。 blablabla。 另一个带有kostenlos的句子。 带有bauseits的sentance3。 blablabla。 另一个带有恶意的观点。 blablabla。”

结果,我希望拥有:

l_lv = [“其中包含kostenlos的“ sentance1”,“其中包含kostenlos的另一个senent2”,“其中包含bauseits的sentance3”,“其中包含bauseits的另一个sentance4”]]

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM