from collections import Counter
# 1:
s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()
c = Counter(s)
# 获取出现频率最高的5个字符
print (c.most_common(5))
"""
运行结果:
[(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]
"""
#2:
c = Counter()
for ch in 'programming':
c[ch] = c[ch] + 1
print("统计字符出现的个数:",c)
"""
运行结果:
统计字符出现的个数: Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})
"""
#3:
s = 'abcbcaccbbad'
l = ['a','b','c','c','a','b','b']
d = {'2': 3, '3': 2, '17': 2}
# Counter 获取各元素的个数,返回字典
print(Counter(s)) # Counter({'c': 4, 'b': 4, 'a': 3})
print(Counter(l)) # Counter({'b': 3, 'a': 2, 'c': 2})
print(Counter(d)) # Counter({3: 3, 2: 2, 17: 1})
"""
运行结果:
Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
Counter({'b': 3, 'a': 2, 'c': 2})
Counter({'2': 3, '3': 2, '17': 2})
"""
#4:
# most_common(int) 按照元素出现的次数进行从高到低的排序,返回前int个元素的字典
m1 = Counter(s)
print(m1) # Counter({'c': 4, 'b': 4, 'a': 3, 'd': 1})
print(m1.most_common(3)) # [('c', 4), ('b', 4), ('a', 3)]
"""
运行结果:
Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
[('b', 4), ('c', 4), ('a', 3)]
"""