我知道我可以通过以下方式在文本/数组中找到一个单词:
if word in text:
print 'success'
Run Code Online (Sandbox Code Playgroud)
我想做的是阅读文本中的一个单词,并根据找到的单词进行多次计数(这是一个简单的计数器任务)。但问题是我真的不知道如何理解read已经读过的单词。最后:统计每个单词出现的次数?
我想过保存在一个数组中(甚至是多维数组,所以保存单词和它出现的次数,或者保存在两个数组中),每次在该数组中出现一个单词时求和1。
那么,当我读一个单词时,我可以不读类似这样的内容吗:
if word not in wordsInText:
print 'success'
Run Code Online (Sandbox Code Playgroud)
sentence = 'a quick brown fox jumped a another fox'
words = sentence.split(' ')
Run Code Online (Sandbox Code Playgroud)
解决方案1:
result = {i:words.count(i) for i in set(words)}
Run Code Online (Sandbox Code Playgroud)
解决方案2:
result = {}
for word in words:
result[word] = result.get(word, 0) + 1
Run Code Online (Sandbox Code Playgroud)
解决方案3:
from collections import Counter
result = dict(Counter(words))
Run Code Online (Sandbox Code Playgroud)