三种方法:
①直接使用dict
②使用defaultdict
③使用Counter

一、直接使用dict

  1. text = "I'm a hand some boy!"
  2. frequency = {}
  3. for word in text.split():
  4. if word not in frequency:
  5. frequency[word] = 1
  6. else:
  7. frequency[word] += 1

二、使用defaultdict

  1. import collections
  2. frequency = collections.defaultdict(int)
  3. text = "I'm a hand some boy!"
  4. for word in text.split():
  5. frequency[word] += 1

三、使用Counter

  1. import collections
  2. text = "I'm a hand some boy!"
  3. frequency = collections.Counter(text.split())