python复习之【Counter计数】
据悉python中库很多很多,没系统学过,许多手动写很麻烦,现在重头学一学【Counter计数】。
collections.Counter可以跟踪计数和频率统计,我们试试看吧。
txt = "They should always bear in mind major issues of the country, be adept at planning for major issues for the country and Party, deliver benefits to the people and win their support, Xi said."
from collections import Counter
counts = Counter(txt.split())
counts
Counter({‘They’: 1,
‘should’: 1,
‘always’: 1,
‘bear’: 1,
‘in’: 1,
‘mind’: 1,
‘major’: 2,
‘issues’: 2,
‘of’: 1,
‘the’: 3,
‘country,’: 1,
‘be’: 1,
‘adept’: 1,
‘at’: 1,
‘planning’: 1,
‘for’: 2,
‘country’: 1,
‘and’: 2,
‘Party,’: 1,
‘deliver’: 1,
‘benefits’: 1,
‘to’: 1,
‘people’: 1,
‘win’: 1,
‘their’: 1,
‘support,’: 1,
‘Xi’: 1,
‘said.’: 1})
单词频次除夕拿了,意不意外?
counts.most_common(2)
[(‘the’, 3), (‘major’, 2)]
counts['for']
2
sum(counts.values())
34
c = Counter('abcdeabcdabcaba') # count elements from a string
c
Counter({‘a’: 5, ‘b’: 4, ‘c’: 3, ‘d’: 2, ‘e’: 1})
sorted(c)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
sum(c.values())
15
Counter
只是一种特殊的字典,字典可以通过提供 iterable 来构建。iterable 中的每个条目都将添加到字典中。
- 点赞
- 收藏
- 关注作者
评论(0)