<p>下面的代码将满足您在问题中提出的要求,但它不太可能是您想要的结果。
代码的一般基础结构应该是正确的,但是您可能希望更改部分匹配的条件(<code>stopword in testword</code>):</p>
<pre><code>def filter_out_stopwords(text, stopwords):
result = []
for word in text.split():
testword = word.lower()
flag = True
for stopword in stopwords:
if stopword in testword:
flag = False
break
if flag:
result.append(word)
return result
' '.join(filter_out_stopwords("My words aren't available give didn't give apple and did happening me", ['are', 'did', 'word', 'able', 'give', 'happen']))
# "My apple and me"
</code></pre>
<p>或者,使用列表理解和<code>all()</code>(<code>any()</code>可以等价地使用):</p>
<pre><code>def filter_out_stopwords(text, stopwords):
return [
word for word in text.split()
if all(stopword not in word.lower() for stopword in stopwords)]
' '.join(filter_out_stopwords("My words aren't available give didn't give apple and did happening me", ['are', 'did', 'word', 'able', 'give', 'happen']))
# "My apple and me"
</code></pre>