Python Program to Count the Frequency of Words in a String
Beginner · Strings
Word frequency means how many times each word appears in a piece of text. This program counts the words of a sentence in a dictionary, with each word as a key and its count as the value, which is where search engines and word clouds start too.
Program
Sentence: The cat sat on the mat and the cat slept the : 3 cat : 2 sat : 1 on : 1 mat : 1 and : 1 slept : 1
How it works
text.lower().split()makes the words lower case and splits them, so "The" and "the" count as the same word.- A new word is added to
frequencywith a count of 1, and a word already there has its count increased. - The output lists the words in the order they first appear, because dictionaries keep the order keys were added in.
- Punctuation stays attached to words in this version, so "cat." and "cat" would be different; the first alternative strips it.
Other ways to write it
Using Counter, with punctuation removed
Counter({'python': 3, 'is': 3, 'great': 1, 'easy': 1, 'and': 1, 'fun': 1})
Most common word: [('python', 3)]Each word has its punctuation stripped and is lower-cased before counting. most_common(1) returns the top word with its count, and on a tie the word seen first wins.
Sorted from most to least frequent
the *** (3) cat ** (2) sat * (1) on * (1) mat * (1) and * (1) slept * (1)
sorted() with key=lambda pair: pair[1] orders the (word, count) pairs by count, reverse=True puts the biggest first, and "*" * count draws a small bar chart.
Try it yourself
Change the program to print only the words that appear more than once.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Frequency of Each Character in a String
- Count the Words in a String
- Count the Frequency of Each Element in a List
- Count Words in a Text File
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Remove Punctuation from a String
- Sort Words in Alphabetical Order
All Python programs · CBSE class 12 practical file · Python exercises