Skip to content

Project: Word Statistics Tool

Build a text tool that counts lines and words, finds a longest word, and ranks frequencies.

19 min read 10 quiz questions

Stage 1: Count lines and words

A triple-quoted string can hold several lines of text. Use splitlines() for lines and split() for words.

Stage 1: Count text pieces
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.

Stage 2: Find a longest word
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.

Stage 3: Make a deterministic top-three table
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.

Stage 4: Complete word statistics tool
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.

Example
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

  1. split() with no arguments cuts on any whitespace.
  2. max(key=len) finds the longest WORD — ties go to the first seen, so 'learning' (8 letters).
  3. A generator expression counts vowels in one pass.

References & Further Reading

Related entries from PyLabs's own reference library.

  • split() (Split text into a list of pieces.)
  • get() (Look up a value safely without raising a KeyError if missing.)
  • items() (Return a dynamic view of all (key, value) pairs in the dictionary.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Set 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
Want another challenge on this module? More coding practice

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 completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/4 complete
Module cheat sheet