0
0

More than 1 year has passed since last update.

collections.Counter

Last updated at Posted at 2020-07-08
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)]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0