Word counter
Paste in some text and get back the number of words, the longest word and the words used most often. Essays with a word limit, speeches timed by the minute, checking which words you overuse: a word counter is useful, and it is a good workout for strings, lists and dictionaries.
Stage 1: the simple counts
text = "Practice makes a person perfect. Practice a little every day."
print("Characters:", len(text))
print("Without spaces:", len(text.replace(" ", "")))
print("Words:", len(text.split()))
print("Sentences:", text.count("."))Output
Characters: 61
Without spaces: 52
Words: 10
Sentences: 2split with no argument cuts at any run of spaces, tabs or new lines, so double spaces do not create empty words.
Stage 2: clean the words
To count how often each word appears, "Practice" and "practice." must be seen as the same word. Turn everything to small letters and strip punctuation from the ends of each word.
import string
text = "Practice makes a person perfect. Practice a little every day."
words = [w.strip(string.punctuation).lower() for w in text.split()]
print(words)Output
['practice', 'makes', 'a', 'person', 'perfect', 'practice', 'a', 'little', 'every', 'day']string.punctuation is a ready-made string of punctuation marks. strip removes any of them from both ends of the word, but leaves marks in the middle alone, so "don't" stays whole.
Stage 3: count each word
The counting pattern from the dictionaries lesson does the job.
import string
text = "Practice makes a person perfect. Practice a little every day."
words = [w.strip(string.punctuation).lower() for w in text.split()]
count = {}
for w in words:
count[w] = count.get(w, 0) + 1
print(count)Output
{'practice': 2, 'makes': 1, 'a': 2, 'person': 1, 'perfect': 1, 'little': 1, 'every': 1, 'day': 1}Python also has a tool made for exactly this: Counter in the collections module. It counts for you and can list the most common items.
from collections import Counter
words = ["practice", "makes", "a", "person", "perfect", "practice", "a", "little"]
count = Counter(words)
print(count.most_common(2))
print(count["practice"], count["missing"])Output
[('practice', 2), ('a', 2)]
2 0A Counter behaves like a dictionary, except that a missing key gives 0 instead of an error. Knowing the manual way first means you understand what Counter is doing.
Stage 4: one function that reports everything
import string
from collections import Counter
SMALL_WORDS = {"a", "an", "the", "is", "of", "to", "and", "in", "it"}
def analyse(text):
words = [w.strip(string.punctuation).lower() for w in text.split()]
words = [w for w in words if w]
useful = [w for w in words if w not in SMALL_WORDS]
return {
"characters": len(text),
"words": len(words),
"different words": len(set(words)),
"longest word": max(words, key=len),
"average word length": round(sum(len(w) for w in words) / len(words), 1),
"most common": Counter(useful).most_common(3),
"minutes to read aloud": round(len(words) / 130, 1),
}
sample = ("The sun rises in the east. The sun gives light and the sun gives heat. "
"Without the sun, life on the earth is not possible.")
for label, value in analyse(sample).items():
print(f"{label:<22}{value}")Output
characters 122
words 25
different words 16
longest word possible
average word length 3.8
most common [('sun', 4), ('gives', 2), ('rises', 1)]
minutes to read aloud 0.2Points worth noticing:
- The second comprehension drops empty strings, which appear when a "word" was only punctuation, such as a lone dash.
- Very common small words are left out of the "most common" list, otherwise "the" wins every time. The set of small words is a setting you can extend.
- The reading time assumes about 130 words a minute, a comfortable speaking pace. It is an estimate. Change the number to suit the speaker.
- The function returns a dictionary and does not print. The loop at the bottom decides how to show it.
Stage 5: read the text from a file
with open("essay.txt", "w", encoding="utf-8") as f:
f.write("Trees give us shade.\nTrees give us fruit.\nPlant more trees.\n")
with open("essay.txt", encoding="utf-8") as f:
text = f.read()
print(len(text.split()), "words on", len(text.splitlines()), "lines")Output
11 words on 3 linesReplace the middle of the program with a call to your analyse function and you have a tool that works on any text file.
Does it work for Hindi?
Yes. Python strings hold any script, and split cuts Hindi or Punjabi text at spaces just the same. Two things differ. lower does nothing, because those scripts have no capital letters. And the Hindi full stop, the danda, is not in string.punctuation, so add it yourself.
import string
text = "पेड़ हमें छाया देते हैं। पेड़ हमें फल देते हैं।"
marks = string.punctuation + "।"
words = [w.strip(marks) for w in text.split()]
print(len(words), "words;", words.count("पेड़"), "times पेड़")Output
10 words; 2 times पेड़Ideas to extend it
- Warn when the text goes over a word limit given by the user.
- Find the longest sentence.
- List every word used only once.
Exercise 1. Write a function count_long_words(text, n) that returns how many words have more than n letters. Test it on a sentence of your choice with n = 5.
Show one answer
import string
def count_long_words(text, n):
words = [w.strip(string.punctuation) for w in text.split()]
return len([w for w in words if len(w) > n])
print(count_long_words("Education is the most powerful weapon.", 5))Output
3Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.
This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.