LESSON 16 · PRACTICE PROJECT21 min

Project: Text Analyzer

Start with text.lower().split(): lower makes case consistent, and split divides on whitespace. Count the resulting words with len. A dictionary can track words already seen, so its length gives the number of unique words.

Combine string methods, a loop, and a dictionary to summarize a sentence.

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Project: Text Analyzer

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Take this sentence: Python is fun and python is useful. How many words are there, and how many different words appear? Count the words once before touching the keyboard. There are seven tokens separated by spaces. Python appears twice with different capitalization, and is appears twice, so there are five distinct words when we ignore letter case. In this project we will write a small text analyzer that reports both numbers. It brings together string methods, a loop, and a dictionary. The goal is not to build a perfect language processor. It is to choose a clear counting rule, implement it, and verify it with a few examples.

  2. 00:41

    We will also see how punctuation and empty text affect the answer. Open the companion lesson in PythonLessonLab if you want to pause and execute the examples yourself. Begin by deciding what this first version means by a word. We will use Python's split method with no argument. It separates the text wherever there is whitespace, including ordinary spaces and line breaks, and it ignores runs of extra whitespace. Before splitting, call lower so uppercase Python and lowercase python become the same value. The expression text lower, then split, returns a list of normalized tokens. In the sample sentence the list contains seven entries.

  3. 01:24

    Use len on that list for the total word count. To find the number of distinct words, we need a structure that remembers each normalized token. A dictionary maps a word to how many times it appears. Start with an empty dictionary named counts. Loop over the token list. For each word, read its previous count with counts get, defaulting to zero when the key is new, then add one. The first Python makes the count one. The second Python makes it two. The same happens for is. When the loop ends, the dictionary has one key for every unique word, so len counts gives five. Return a new dictionary with two named results, words and unique.

  4. 02:07

    This is more explicit than returning a bare pair whose positions a caller has to remember. The code calling the function prints a sentence using those two result keys. Run the completed sample and compare its output with your prediction: seven words and five unique words. Now consider an empty string. Lowering it leaves an empty string. Splitting produces an empty list, the loop executes zero times, and both counts are zero. No special branch is needed. Try text consisting only of spaces and predict the same result. Next consider Go go GO. After lower, each token is go.

  5. 02:47

    The total is three, but the unique count is one. This small test reveals a missing lower call immediately. Our counting rule treats punctuation as part of a token. The words code and code followed by an exclamation mark are different dictionary keys. That is not necessarily a bug; it is the rule we chose for this beginner version. If the intended use is a more realistic report, we need a different tokenization rule. The website's deeper guide shows a regular expression that extracts English letter sequences and keeps an apostrophe inside a contraction. It then lowercases the tokens and counts them.

  6. 03:27

    That example handles a comma after Python and the contraction don't, while stating its limits: it is not a universal rule for every language or every writing system. Another useful extension is a frequency ranking. Once counts stores values, sort its word and count pairs by descending count, then alphabetically for ties. A tie rule matters because predictable output is easier to verify and explain. The deeper guide prints red three times, blue twice, and green once. Try changing one red to blue and predict how the ranking changes. Finally, analyze multiline text. Split with no argument already sees words across line breaks, but you may also want a separate count of nonempty lines.

  7. 04:14

    The guide demonstrates checking each line with strip and counting its words. The lesson's basic function stays small; these extensions show where a real text reporting tool might go next. The first mistake is confusing characters with words. Len of the original string counts letters, spaces, and punctuation, so it cannot answer how many words the sentence contains. Apply len to the token list after split. The second mistake is forgetting to normalize case. Without lower, Python and python occupy different dictionary keys and the unique count becomes too high for our chosen rule. The third mistake is assuming split removes punctuation.

  8. 04:57

    It does not: code and code with an exclamation mark stay different. That behavior is fine when documented, but it should not surprise a reader. Print the token list when a count looks wrong. Seeing the actual list is often faster than guessing which part of the loop failed. For a new tokenization rule, write down examples that should count as the same word before changing the code. Pause now and complete analyze text in the lesson editor. First test the sample sentence and predict seven total words, five unique. Then test an empty string; both values should be zero. Test Go go GO and expect three total words but one unique word.

  9. 05:38

    These three cases cover an ordinary input, a boundary case, and the case-normalization rule. Run the task checker only after comparing your predictions with the program's output. The checker uses more than the displayed sample, so merely printing seven and five will not satisfy the task. Finish the three-question quiz to mark the project complete. If you want an extra challenge, return the most frequent word as well. Decide how you will break a tie before writing the sort; alphabetical order is a simple deterministic choice. The lesson link on screen has all three deeper walkthroughs, executable examples with expected output, typical mistakes, and the console you can use to experiment without installing anything.

Understand the concept

For each word, increase its count with counts.get(word, 0) + 1. Return a small dictionary with total and unique counts. This project treats punctuation as part of a word: 'code' and 'code!' count separately. That simple rule keeps the first version predictable.

The function should also handle an empty string. split() returns an empty list, so both counts become zero. Once your checked solution works, try adding a third field for the most frequent word.

  • lower() makes case-insensitive comparison possible
  • split() separates whitespace-delimited words
  • A dictionary records word frequencies

See it step by step

Read the code, predict the output, then compare it with the result.

01. Normalize and split

PYTHON
words = "Code code twice".lower().split()
print(words)
EXPECTED OUTPUT
['code', 'code', 'twice']

lower turns both versions of Code into the same word; split creates a list.

02. Count total words

PYTHON
words = "one two three".split()
print(len(words))
EXPECTED OUTPUT
3

The list has three items after splitting on spaces.

03. Count distinct words with a dictionary

PYTHON
counts = {}
for word in ["a", "b", "a"]:
    counts[word] = counts.get(word, 0) + 1
print(counts)
print(len(counts))
EXPECTED OUTPUT
{'a': 2, 'b': 1}
2

Dictionary keys are unique, so two a entries still create only one key.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Choose a definition of word

A word count depends on the rule you choose. Splitting on whitespace treats 'Python,' and 'Python' as different tokens because punctuation stays attached. A more deliberate rule can pull letter sequences out of the text first. The regular expression below keeps English letters and optionally an apostrophe within a word, so 'don't' remains one token. It deliberately does not handle every language or every kind of punctuation.

Normalize case after extracting tokens so different capitalization does not create extra dictionary keys. This is a product decision: for some reports, 'US' and 'us' should remain different. State the rule near the code and test it with examples that include punctuation, contractions, and an empty string. Try replacing the comma with an exclamation mark and predict whether the result changes.

PYTHON
import re
text = "Python, python! Don't stop."
tokens = re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", text)
words = [token.lower() for token in tokens]
print(words)
print(len(words))
EXPECTED OUTPUT
['python', 'python', "don't", 'stop']
4
Follow the reasoning
  1. findall extracts matching token strings and ignores the comma, exclamation mark, and period.
  2. lower makes the two spellings of Python identical for counting.
  3. Test an empty string; the result should be an empty list and a count of zero.
02 / 03

Rank frequent words predictably

A frequency dictionary is useful when you want more than a total and a unique count. To show the most frequent words, sort pairs of (word, count) by descending count. Ties need a second rule; alphabetical order makes results stable even when the original sentence order changes. This matters for screenshots, tests, and readers who want the same example output each time.

Python's sorted function accepts a key that maps each pair to the values used for ordering. A negative count sorts large counts first, while the word itself breaks ties. The example returns a new list and leaves the counts dictionary available for other reports. Change the final 'red' to 'blue' and predict which word appears first.

PYTHON
words = "red blue red green blue red".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
ranking = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
for word, count in ranking:
    print(f"{word}: {count}")
EXPECTED OUTPUT
red: 3
blue: 2
green: 1
Follow the reasoning
  1. The dictionary stores one count per distinct word.
  2. The sorting key uses negative count for descending frequency and word for ties.
  3. Try input with equal counts, such as 'red blue', and predict alphabetical order.
03 / 03

Analyze several lines as one report

Text often arrives as more than one sentence. A line break is whitespace, so split() can count every word across lines, but line boundaries can still be useful. For example, you may want to know how many nonempty lines a note contains in addition to its word count. The code below records both without changing the original text.

Avoid calling strip() on the whole source if leading or trailing spacing is meaningful to your application. Here strip() is used only to decide whether a line has visible content. Splitting each line separately makes the decision easy to inspect. Try adding a line containing only spaces; the number of nonempty lines should stay the same.

PYTHON
text = "First line has words\n\nSecond line too\n"
nonempty_lines = 0
total_words = 0
for line in text.splitlines():
    if line.strip():
        nonempty_lines += 1
        total_words += len(line.split())
print(f"Lines: {nonempty_lines}")
print(f"Words: {total_words}")
EXPECTED OUTPUT
Lines: 2
Words: 7
Follow the reasoning
  1. splitlines separates the source into three lines, including one blank line.
  2. The blank line is ignored; four words plus three words produce seven.
  3. Insert another blank or spaces-only line and predict both totals.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnComplete analyze_text(text) so it returns a dictionary with keys words and unique. Count words after lower().split(), and use a dictionary to track unique words. The prepared sentence should print Words: 7; unique: 5. Handle empty text too.
Need a hint?

Make words = text.lower().split(). Start counts = {}. Loop over words and set counts[word] = counts.get(word, 0) + 1. Return {'words': len(words), 'unique': len(counts)}.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What does 'Hi hi'.lower().split() produce?

    02.Why use counts.get(word, 0)?

    03.How many unique words are in 'red blue red'?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Counting the text's characters

    COMMON MISTAKE
    word_count = len(text)
    FIX
    word_count = len(text.split())

    What happens: 'red blue' reports eight characters instead of two words.
    Split the text first when you want a word count.

    Treating capitalization as a new word

    COMMON MISTAKE
    words = text.split()
    FIX
    words = text.lower().split()

    What happens: 'Code' and 'code' become separate dictionary keys.
    Normalize case before counting for a case-insensitive report.

    Browse this lesson’s problem fixes

    Sources and further reading