[PYTHON] collections.Counter

lesson.py


import collections

d = {}
l = ['a', 'a', 'a', 'b', 'b', 'c']
for word in l:
    if word not in d:
        d[word] = 0
    d[word] += 1
print(d)

d = {}
for word in l:
    d.setdefault(word, 0)
    d[word] += 1
print(d)

d = collections.defaultdict(int)
for word in l:
    d[word] += 1
print(d)

c = collections.Counter()
for word in l:
    c[word] += 1
print(c)
print(c.most_common(2)) #Show the top two
print(c.values())

import re
with open('lesson.py', 'r') as f:
    words = re.findall(r'\w+￿', f.read().lower())
    print(words) #why[]become
    print(collections.Counter(words).most_common(20))

Execution result:

{'a': 3, 'b': 2, 'c': 1}
{'a': 3, 'b': 2, 'c': 1}
defaultdict(<class 'int'>, {'a': 3, 'b': 2, 'c': 1})
Counter({'a': 3, 'b': 2, 'c': 1})
[('a', 3), ('b', 2)]
dict_values([3, 2, 1])
[]
[]

Recommended Posts

collections.Counter
Use collections.Counter