Project: Word Statistics Tool
Build a text tool that counts lines and words, finds a longest word, and ranks frequencies.
Stage 1: Count lines and words
A triple-quoted string can hold several lines of text. Use splitlines() for lines and split() for words.
text = """red blue red
green blue red
yellow"""
lines = text.splitlines()
words = text.split()
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
The text has three lines and six space-separated words. len() counts the items in each list.
Stage 2: Find the longest word
The max() function can choose the longest word when you give it key=len.
text = """red blue red
green blue red
yellow"""
words = text.split()
longest_word = max(words, key=len)
print(f"Longest word: {longest_word}")
max() compares the word lengths instead of the words themselves. yellow has the most letters.
Stage 3: Count and sort frequencies
A dictionary can map each word to its count. Sort dictionary items by negative count first, then by the word, so ties always appear in alphabetical order.
words = "red blue red green blue red yellow".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
top_words = sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:3]
print(f"{'Word':<7} {'Count':>5}")
for word, count in top_words:
print(f"{word:<7} {count:>5}")
counts.get(word, 0) starts a new word at zero. The sort rule puts larger counts first and uses alphabetical order when counts match.
Stage 4: Finish the word statistics tool
Now combine the counts, longest word, frequency dictionary, and ranked table in one report.
text = """red blue red
green blue red
yellow"""
lines = text.splitlines()
words = text.split()
longest_word = max(words, key=len)
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
top_words = sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:3]
print("Word Statistics")
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Longest word: {longest_word}")
print()
print("Top 3 words")
print(f"{'Word':<7} {'Count':>5}")
for word, count in top_words:
print(f"{word:<7} {count:>5}")
The final report is stable every time it runs. Its top-three table uses the requested count-descending, word-ascending sort rule.
Key points
- Triple-quoted strings can contain multiple lines.
- splitlines() and split() turn text into lists you can count.
- max(words, key=len) finds a longest word.
- A dictionary maps words to their frequencies.
- Sort by (-count, word) for a deterministic ranking.
Worked example
Analyse a sentence from an essay: word count, longest word and vowel tally — the core of any text tool.
text = "learning python opens doors" words = text.split() longest = max(words, key=len) vowels = sum(1 for ch in text if ch in "aeiou") print(len(words), longest, vowels)
How it works, step by step
- split() with no arguments cuts on any whitespace.
- max(key=len) finds the longest WORD — ties go to the first seen, so 'learning' (8 letters).
- A generator expression counts vowels in one pass.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetSet text to "cat dog cat bird". Build a dictionary named counts, then a list named top_words sorted by count descending and word ascending. Print exactly:
Top words:
cat: 2
bird: 1
dog: 1
# Create text and split it into words # Count words and create the sorted top_words list
Check yourself
Project: Word Statistics Tool quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.