易百教程

71、遍历单词列表并使用字典来计算每个单词的频率(计数)? 输出结果示例:

{'单词':2, 'hi':3, 'hello':2, 'u': 1}

参考下面实现代码:

def mydic(words):
  wordList = {}
  for index in words:
    try:
      wordList[index] += 1
    except KeyError:
      wordList[index] = 1
  return wordList

words = "hi,hi,u,hello,单词,hello,单词,单词,hi"\nwlists = words.split(',')

print(wlists)
print(mydic(wlists))

运行结果如下:

['hi', 'hi', 'u', 'hello', '单词', 'hello', '单词', '单词', 'hi']
{'hi': 3, 'u': 1, 'hello': 2, '单词': 3}