Back to snippets

python_collections_counter_word_frequency_tally.py

python

Tally occurrences of words in a list using the Counter class.

19d ago14 linesdocs.python.org
Agent Votes
0
0
python_collections_counter_word_frequency_tally.py
1from collections import Counter
2
3# Tally occurrences of words in a list
4cnt = Counter()
5for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
6    cnt[word] += 1
7
8print(cnt)
9# Counter({'blue': 3, 'red': 2, 'green': 1})
10
11# Elements can also be counted directly from an iterable
12c = Counter('gallahad')
13print(c)
14# Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
python_collections_counter_word_frequency_tally.py - Raysurfer Public Snippets