Editor

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

word_frequency.py
text = "The cat sat on the mat and the cat slept" # or: text = input("Enter a sentence: ")
frequency = {}
for word in text.lower().split():
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
print("Sentence:", text)
for word, count in frequency.items():
print(word, ":", count)
Output
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

  1. text.lower().split() makes the words lower case and splits them, so "The" and "the" count as the same word.
  2. A new word is added to frequency with a count of 1, and a word already there has its count increased.
  3. The output lists the words in the order they first appear, because dictionaries keep the order keys were added in.
  4. 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

Using Counter, with punctuation removed
import string
from collections import Counter
text = "Python is great. Python is easy, and Python is fun!"
words = [w.strip(string.punctuation).lower() for w in text.split()]
frequency = Counter(words)
print(frequency)
print("Most common word:", frequency.most_common(1))
Output
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

Sorted from most to least frequent
text = "the cat sat on the mat and the cat slept"
frequency = {}
for word in text.split():
frequency[word] = frequency.get(word, 0) + 1
ranked = sorted(frequency.items(), key=lambda pair: pair[1], reverse=True)
for word, count in ranked:
print(f"{word:6} {'*' * count} ({count})")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises