擅长:python、mysql、java
<p>如果使用position表示句子中的第n个单词,则可以执行以下操作:</p>
<pre><code>words = sentence.split(' ')
if keyword in words:
pos = words.index(keyword)
</code></pre>
<p>这将在每次出现空格后拆分句子,并将句子保存在列表中(按单词顺序)。如果句子包含关键字,<a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow" title="list.index()">list.index()</a>将找到它的位置。</p>
<p><strong>编辑</strong>:</p>
<p>if语句是确保关键字在语句中所必需的,否则list.index()将引发ValueError。</p>