Python programs · Strings
Python program to count the frequency of words
Counting how often each word appears is the standard use for a dictionary.
Approach
- Read a sentence and split it into words.
- Keep a dictionary that maps each word to its count.
- Print every word with its count.
The program
text = input().lower() counts = {} for word in text.split(): counts[word] = counts.get(word, 0) + 1 for word, count in counts.items(): print(word, count)
Sample run
Input
the cat and the dog and the bird
Output
the 3 cat 1 and 2 dog 1 bird 1
How the code works
counts.get(word, 0) returns the current count, or 0 if the word has not been seen, and the + 1 records the new sighting. Using .get avoids the KeyError that counts[word] would cause for a new word. Dictionaries keep the order in which keys were first added, which is why the output follows the sentence.
Try changing it
- Print the words from most to least frequent using
sorted(counts.items(), key=lambda pair: pair[1], reverse=True). - Remove punctuation before counting.
Common mistakes
- Writing
counts[word] += 1for a word that is not in the dictionary yet, which raises a KeyError. - Forgetting
.lower(), so "The" and "the" are counted separately.