擅长:python、mysql、java
<p>如果可能的话用Katrielex的答案,它比我的更干净。如果您没有Python 2.7(像我一样),这可能对您有用:</p>
<pre><code>sentence = "Dogs are great pets and hamsters are bad pets. That is why I want a dog"
scores = {'dog' : 5, 'hamster' : -2}
occurrences = {}
for key in scores:
m = re.findall(key, sentence , re.IGNORECASE)
occurrences[key] = len(m)
totalScore = 0
for word in occurrences:
totalScore += scores.get(word.lower(), 0) * occurrences[word]
print totalScore
</code></pre>
<p>我在你的分数字典里做了“dogs”->;“dog”,假设这是个打字错误。如果你把它改回来,你的结果是3而不是复数。在</p>