^^Python. collections.Counter([iterable-or-mapping])

docs.python.org/3.8/library/collections.html

 

class collections.Counter([iterable-or-mapping])

Counter:  dict subclass, for counting hashable objects.

  1. elements stored as dictionary keys, their counts stored as dictionary values.
  2. Counts  integer values (signed)
  3. Counter class is similar to bags or multisets in other languages.

 

Counter()    builds a dictionary of int

A counter tool is provided to support convenient and rapid tallies.

Tally occurrences of elements in a list

from collections import Counter
cnt = Counter()
L = ['red', 'blue', 'red', 'green', 'blue', 'blue']
for e in L:
    cnt[e] += 1
 
print(cnt)
 Counter({'blue': 3, 'red': 2, 'green': 1}) 

 

Counter puo' essere inizializzato

con la stessa espressione che ha come suo print

Counter({'blue': 3, 'red': 2, 'green': 1}) 

reading a key not in counter, not raise KeyError, and return 0

the key is not inserted (with the value of 0)

cnt['a']      # 'a' not a key
 0
'a' in cnt    # 'a' not inserted
 False    

Find the most common words in a text

from collections import Counter
import re
words = re.findall(r'\w+', open('pinocchio.txt').read().lower())
Counter(words).most_common(20)

Selezionare le parole con 1 ricorrenza

one_recur = []       # create a void list
for e in Counter(words).most_common():
    if e[1] == 1:
        one_recur.append(e[0])

1-line cmd (pythonic list comprehension)

L = Counter(words).most_common()

[e[0] for e in L if e[1] == 1]
syntax
[f(x) for x in y if g(x)]

Regular expression. Modulo re.py
https://docs.python.org/3.8/library/re.html