且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python字典计算一个单词出现的次数并链接到字典中的单词

更新时间:2021-12-06 08:53:07

有一个名为 collections.Counter 的专用类来执行这样的任务:

There is dedicated class named collections.Counter to perform such tasks:

import collections
words = "hey hey hello"
c = collections.Counter(words.split())
print c  # Counter({'hey': 2, 'hello': 1})

明确的解决方案是这样的:

Explicit solution would be something like this:

wordsCount = {}
words = []  # list of words
for word in words:
  if word not in wordsCount:
    wordsCount[word] = 0
  wordsCount[word] += 1