python - 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']
解决方案
您无权访问列表理解/生成器表达式等之外的变量。该错误是有效的,因为当您尝试附加它时未定义“单词”。
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)
推荐阅读
- python - 无法通过套接字连接到本地 MySQL 服务器\'/cloudsql/my_project:us-central1:my_instance\'
- libtorch - 如何修复:CMake 构建成功后 Visual Studio 中出现“未找到torch.dll”错误
- python - Flask 请求:确定确切路径,包括是否有问号
- bash - 通过 bash 脚本运行工具
- java - 如何使用 escpos-2.2 jar & jSerialComm-2.5.0 jar 在热敏收据打印机上打印收据
- python-3.x - KivyMD 中的 MDDropDownMenu 错误(适用于 Python 3.6 上的 Kivy)
- javascript - vue2-google-maps 如何使用 Embed API “放置模式”
- pdf - PDFBOX - 签署 PDF 时,不调用 SignatureInterface 的签名
- php - PHP 和 SQL 中的日期转换
- aspnetboilerplate - 如何取消 BackgroundJob 或让新作业不重试?