A Python Counter groups hashable objects into bins and records how often each occurs. Its keys are the distinct objects, and its values are their counts. For language processing, those objects can be tokens such as words and punctuation. section 1.5.3 section 3.1
Count a greeting
from collections import Counter tokens = "Good morning Rosa!".split() counts = Counter(tokens) print(counts) Each token has a count of 1. The exclamation mark remains attached to “Rosa!” because split() separates the string on whitespace; token cleanup changes what gets counted. section 1.5.3
A Counter can represent a bag of words: it records token frequencies but not their sequence in the sentence. The choice of tokenizer matters. If punctuation is a separate token, it gets its own count and may be among the most frequent entries. section 1.5.3 section 3.1
>>> from collections import Counter
>>> bag_of_words = Counter(tokens)
>>> bag_of_words
Counter({',': 5, 'and': 2, 'It': 1, 'has': 1, 'also': 1, 'arisen': 1, ...})
A tokenized sentence produces a Counter in which the comma occurs five times and “and” occurs twice. section 3.1
Use counts.most_common(3) to inspect the three most frequent entries. Converting the counts to a pandas Series makes it convenient to divide each count by the total number of tokens. In the example sentence, 18 distinct tokens account for 23 occurrences, so the comma’s relative frequency is 5/23, or about 0.217. section 3.1
For comparing documents as vectors, give each vocabulary token a consistent position across documents. A Counter supplies the counts, but relying on each Counter’s key order alone does not establish that shared alignment. section 3.1


