擅长:python、mysql、java
<p>您想根据文件是否包含某些文本来创建文件列表</p>
<p>有一个Python内置函数<a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow noreferrer">^{<cd1>}</a>可以做到这一点<code>filter</code>接受一个返回布尔值和iterable(例如列表)的函数,并返回一个迭代器,该迭代器遍历函数返回的原始iterable中的元素<code>True</code></p>
<p>因此,首先您可以编写该函数:</p>
<pre><code>def contains_terms(filepath, terms):
with open(filepath) as f:
content = f.read()
return any(term in content for term in terms)
</code></pre>
<p>然后在<code>filter</code>中使用它,并根据结果构造一个<code>list</code>:</p>
<pre><code>file_list = list(filter(lambda f: not contains_terms(f, lst_exclusion_terms), file_list))
</code></pre>
<p>当然,<code>lambda</code>是必需的,因为<code>contains_terms</code>接受2个参数,如果术语在文件中,则返回<code>True</code>,这在某种程度上与您想要的相反(但从函数本身的角度来看,排序更有意义)。您可以根据您的用例专门化该函数,并消除对<code>lambda</code>的需要</p>
<pre><code>def is_included(filepath):
with open(filepath) as f:
content = f.read()
return all(term not in content for term in lst_exclusion_terms)
</code></pre>
<p>定义此函数后,对<code>filter</code>的调用更加简洁:</p>
<pre><code>file_list = list(filter(is_included, file_list))
</code></pre>