Strings · intermediate
Python Program to Count the Frequency of Words in a String
Count how often each word appears in a text in Python with a dictionary and dict.get(), then with collections.Counter, ignoring case and punctuation.
- dictionaries
- dict.get()
- str.split()
- sorted() with a key
- collections.Counter
Counting words is the first step of many text tasks: keyword analysis, search indexes and word clouds. The program splits the text into words, cleans each one and counts them in a dictionary.
The program
text = """The cat sat on the mat.
The dog sat on the log."""
counts = {}
for word in text.lower().split():
word = word.strip(".,!?;:")
counts[word] = counts.get(word, 0) + 1
for word, n in sorted(counts.items(), key=lambda item: (-item[1], item[0])):
print(f"{word:<4} {n}")the 4
on 2
sat 2
cat 1
dog 1
log 1
mat 1How it works
- lower() makes "The" and "the" the same word, and split() with no argument splits on any whitespace, including line breaks.
- strip(".,!?;:") removes punctuation from both ends of each word, so "mat." becomes "mat".
- counts.get(word, 0) returns the current count, or 0 for a new word, and the count goes up by one.
- sorted() with the key (-count, word) puts the most frequent words first and breaks ties alphabetically. {word:<4} pads the word to four characters so the numbers line up.
Watch it run line by line
Watch the counts dictionary in the global frame: it gains a key for each new word, and the highlighted entry shows the count that just went up.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With collections.Counter
Counter does the counting for you, and most_common(n) returns the n most frequent words. Use it in real code.
from collections import Counter
text = "the cat sat on the mat the end"
counts = Counter(text.split())
print(counts.most_common(2))
print(counts["cat"], counts["dog"])[('the', 3), ('cat', 1)]
1 0Common mistakes
- Writing counts[word] += 1 for a word that is not in the dictionary yet raises KeyError. Use get(), setdefault(), defaultdict(int) or Counter.
- Splitting with split(" "): two spaces in a row then produce empty strings that get counted as words.
- Not stripping punctuation, so "mat" and "mat." are counted as different words.
Try it yourself
- Ignore common words such as "the", "on" and "a" with a stop-word set.
- Count letters instead of words and print a simple bar chart with "#" characters.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.