from collections import Counter
text = 'hello world hello world hello hello world hello world'
print(Counter(text.split())
一些Counter常用的方法
| Counter()
|
| Note: If a count is set to zero or reduced to zero, it will remain
| in the counter until the entry is deleted or the counter is cleared:
|
| >>> c = Counter('aaabbc')
| >>> c['b'] -= 2 # reduce the count of 'b' by two
| >>> c.most_common() # 'b' is still in, but its count is zero
| [('a', 3), ('c', 1), ('b', 0)]
| elements(self)
| Iterator over elements repeating each as many times as its count.
|
| >>> c = Counter('ABCABC')
| >>> sorted(c.elements())
| ['A', 'A', 'B', 'B', 'C', 'C']
|
| # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
| >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
| >>&g

本文介绍了如何使用Python的collections.Counter模块来统计文本中单词出现的次数,详细讲解了Counter类的一些常见方法。
最低0.47元/天 解锁文章

4424





