擅长:python、mysql、java
<p>您可以拆分句子并将其传递给<a href="https://docs.python.org/3.7/library/collections.html#collections.Counter" rel="nofollow noreferrer">^{<cd1>}</a>。有了它,你可以在单词列表中查找计数。例如:</p>
<pre><code>from collections import Counter
string = "Cup Noodles Chicken Vegetable Noodles"
listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef']
counts = Counter(string.split())
[counts[word] for word in listWords]
# [2, 0, 0, 0, 1, 0, 0, 0]
</code></pre>
<h3>不带计数器()
<p>当然,您可以在没有<code>Counter()</code>的情况下执行此操作。您只需要处理第一次尝试访问密钥时发生的<code>KeyError</code>。然后可以使用<code>get(word, 0)</code>在查找单词时返回默认值0。比如:</p>
<pre><code>string = "Cup Noodles Chicken Vegetable Noodles"
listWords = ['Noodles', 'Instant', 'Flavour', 'Ramen', 'Chicken', 'Flavor', 'Spicy', 'Beef']
counts = {}
for word in string.split():
try:
counts[word] += 1
except KeyError:
counts[word] = 1
[counts.get(word, 0) for word in listWords]
# still [2, 0, 0, 0, 1, 0, 0, 0]
</code></pre>