lesson.py
import collections
import re
l = ['a', 'a', 'a', 'b', 'b', 'c']
c = collections.Counter()
for word in l:
c[word] += 1
print(c)
print(c.most_common(2)) #上位2つを表示
print(c.values())
with open('lesson.py', encoding='utf-8') as f:
words = re.findall(r'\w+', f.read().lower())
print(words)
print(collections.Counter(words).most_common(20))
実行結果:
Counter({'a': 3, 'b': 2, 'c': 1})
[('a', 3), ('b', 2)]
dict_values([3, 2, 1])
['import', 'collections', 'import', 're', 'l', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'collections', 'counter', 'for', 'word', 'in', 'l', 'c', 'word', '1', 'print', 'c', 'print', 'c', 'most_common', '2', '上位2つを表示', 'print', 'c', 'values', 'with', 'open', 'lesson', 'py', 'encoding', 'utf', '8', 'as', 'f', 'words', 're', 'findall', 'r', 'w', 'f', 'read', 'lower', 'print', 'words', 'print', 'collections', 'counter', 'words', 'most_common', '20']
[('c', 6), ('print', 5), ('collections', 3), ('a', 3), ('words', 3), ('import', 2), ('re', 2), ('l', 2), ('b', 2), ('counter', 2), ('word', 2), ('most_common', 2), ('f', 2), ('for', 1), ('in', 1), ('1', 1), ('2', 1), ('上位2つを表示', 1), ('values', 1), ('with', 1)]