<p>正则表达式在这方面可能有点过头了。我会用<code>in</code>。你知道吗</p>
<h2>例1:</h2>
<p>考虑到返回<code>1</code>或<code>0</code>的要求,我实现<code>findphrase()</code>的方法是:</p>
<pre><code>>>> def findphrase(phrase, to_find):
... if to_find.lower() in phrase.lower():
... return 1
... else:
... return 0
...
>>> phrase = "I'm not well today."
>>> to_find = 'not well'
>>> in_phrase = findphrase(phrase, to_find)
>>> assert in_phrase == 1
>>>
</code></pre>
<p>注意使用<code>to_find.lower()</code>和<code>phrase.lower()</code>来确保资本化并不重要。你知道吗</p>
<h2>例2:</h2>
<p>但坦白说,我不知道你为什么要返回1或0。我只需要返回一个布尔值,这将使:</p>
<pre><code>>>> def findphrase(phrase, to_find):
... return to_find.lower() in phrase.lower()
...
>>> phrase = "I'm not well today."
>>> to_find = "not well"
>>> in_phrase = findphrase(phrase, to_find)
>>> assert in_phrase == True
>>>
</code></pre>
<p>如果您确实需要将结果用作<code>1</code>或<code>0</code>(如果您重写<code>howareyou()</code>函数,则不会这样做),则<code>True</code>和<code>False</code>分别转换为<code>1</code>和<code>0</code>:</p>
<pre><code>>>> assert int(True) == 1
>>> assert int(False) == 0
>>>
</code></pre>
<h2>附加说明</h2>
<p>在<code>howareyou()</code>函数中,有许多错误。您将<code>findphrase()</code>称为<code>findphrase('not well')(howis)</code>。只有从<code>findphrase()</code>(闭包)返回函数时,这才有效,如下所示:</p>
<pre><code>>>> def findphrase(var):
... def func(howis):
... return var.lower() in howis.lower()
... return func
...
>>> phrase = "I'm not well today."
>>> to_find = "not well"
>>> in_phrase = findphrase(to_find)(phrase)
>>> assert in_phrase == True
>>>
</code></pre>
<p>这是因为函数只是Python中的另一种类型的对象。它可以像任何其他对象一样返回。如果您按照以下思路进行操作,则可能需要使用这样的构造:</p>
<pre><code>>>> def findphrase(var):
... def func(howis):
... return var.lower() in howis.lower()
... return func
...
>>> phrases = ["I'm not well today.",
... "Not well at all.",
... "Not well, and you?",]
>>>
>>> not_well = findphrase('not well')
>>>
>>> for phrase in phrases:
... in_phrase = not_well(phrase)
... assert in_phrase == True
...
>>>
</code></pre>
<p>这是因为将<code>findphrase('not well')</code>的结果赋给变量<code>not_well</code>。这将返回一个函数,然后可以将其作为<code>not_well(phrase)</code>调用。执行此操作时,它会将提供给<code>not_well()</code>的变量<code>phrase</code>与提供给<code>findphrase()</code>的变量<code>var</code>进行比较,该变量作为<code>not_well()</code>命名空间的一部分存储。你知道吗</p>
<p>但在本例中,您可能真正想做的是用两个参数定义<code>findphrase()</code>函数,就像前两个示例中的一个。你知道吗</p>
<p>你也在使用<code>findphrase(...) is 1</code>。你可能想要的是<code>findphrase(...) == 1</code>或者,更像Python的,<code>if findphrase(...):</code>。你知道吗</p>