liveBook · Manning

Counter

As explained in Natural Language Processing in Action, Second Edition

A Python Counter is a mapping type that counts hashable objects and stores each object with its frequency.

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

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Defines keys and counts, then demonstrates frequency ranking and normalization with pandas; notes the need for consistent vector positions.
Examples
Counts greeting tokens and spaCy-tokenized sentences and article content about algorithmic bias.
What it assumes
Assumes familiarity with tokens and dictionaries while defining Counter keys as unique objects and values as counts.
What you can do after
Apply collections.Counter and pandas to inspect token counts, rank common tokens, and calculate relative frequencies.
How it connects
Connects tokenization, bag of words, vector space models, and term frequency.

Also explained in

Compare how 3 books explain Counter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.