Python Program to Count the Frequency of Words in a String
Beginner Strings
Counts how many times each word appears in a sentence, with a dictionary that has the words as keys and their counts as values.
Word frequency is how many times each word appears in a piece of text. In the tongue twister "red lorry yellow lorry
red lorry yellow lorry", lorry appears 4 times, and red and yellow twice each. A dictionary suits the job: each
word is a key, and its value is how many times it has been seen so far.
Program
def word_frequency(text):
"""How many times each word appears in text, as a dict."""
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
sentence = "Red lorry yellow lorry red lorry yellow lorry"
print("Word counts:", word_frequency(sentence))
Open in the editor Download word_frequency.py
Output
Word counts: {'red': 2, 'lorry': 4, 'yellow': 2}
How it works
Step through the program line by line: each step below shows up as its line runs.
-
countsstarts as an empty dictionary. -
lower()makesRedandredthe same word, andsplit()breaks the text into a list of words at the spaces. The loop takes the words one by one. -
counts.get(word, 0)is the word's count so far, or 0 when the word hasn't been seen yet, wherecounts[word]would stop with aKeyError(dictionaries). Adding 1 and storing it back counts this one. - The function returns the finished dictionary.
- The program counts the words of the tongue twister and prints the dictionary.
The first five words:
word |
counts.get(word, 0) |
counts after |
|---|---|---|
red |
0 | {'red': 1} |
lorry |
0 | {'red': 1, 'lorry': 1} |
yellow |
0 | {'red': 1, 'lorry': 1, 'yellow': 1} |
lorry |
1 | {'red': 1, 'lorry': 2, 'yellow': 1} |
red |
1 | {'red': 2, 'lorry': 2, 'yellow': 1} |
The last three words take lorry to 4 and yellow to 2. A dictionary keeps its keys in the order they were added, so
the words print in the order they first appear.
Other ways to write it
With collections.Counter
Counter from the collections module counts a list in one step. It's a dictionary with
extras, such as most_common(), which lists the words from the most frequent down.
from collections import Counter
def word_frequency(text):
return Counter(text.lower().split())
counts = word_frequency("the cat and the hat and the bat")
print(counts.most_common(2))With an if statement
Without get(), the loop checks whether the word is already a key: if it is, its count goes up by 1; if not, it
starts at 1.
def word_frequency(text):
counts = {}
for word in text.lower().split():
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print(word_frequency("To be or not to be"))Try it yourself
- Add punctuation, as in "Red lorry, yellow lorry.":
lorry,andlorry.count as different words. Remove it withword.strip(".,!?")before counting. - Print each word and its count on a line of its own, with a
forloop overcounts.items(). - Find the most frequent word with
max(counts, key=counts.get). - Count letters instead of words, by looping over the text itself instead of
text.split().