我目前在Python 3.x中有以下代码:-
lst_exclusion_terms = ['bob','jenny', 'michael']
file_list = ['1.txt', '2.txt', '3.txt']
for f in file_list:
with open(f, "r", encoding="utf-8") as file:
content = file.read()
if any(entry in content for entry in lst_exclusion_terms):
print(content)
我的目标是查看列表文件列表中每个文件的内容。在查看内容时,我想检查列表中是否存在lst_排除项。如果有,我想从列表中删除该条目
因此,如果“bob”在2.txt的内容中,它将从列表中删除(弹出)
我不确定如何用命令替换我的print(content)
,以标识正在检查的项目的当前索引号,然后将其删除
有什么建议吗?谢谢
我以前有过这样的愿望,在迭代时需要删除列表项。通常建议只重新创建一个包含所需内容的新列表here
但是,以下是一种快速而肮脏的方法,可以从列表中删除该文件:
在本例中,文件
3.txt
已从列表中删除,因为它与lst_exclusion_terms
匹配以下是每个文件中使用的内容:
您想根据文件是否包含某些文本来创建文件列表
有一个Python内置函数^{} 可以做到这一点
filter
接受一个返回布尔值和iterable(例如列表)的函数,并返回一个迭代器,该迭代器遍历函数返回的原始iterable中的元素True
因此,首先您可以编写该函数:
然后在
filter
中使用它,并根据结果构造一个list
:当然,
lambda
是必需的,因为contains_terms
接受2个参数,如果术语在文件中,则返回True
,这在某种程度上与您想要的相反(但从函数本身的角度来看,排序更有意义)。您可以根据您的用例专门化该函数,并消除对lambda
的需要定义此函数后,对
filter
的调用更加简洁:相关问题 更多 >
编程相关推荐