…
…
Count the lines, words, and sentences of a short story; get past the lowercase trap with the German letter ß, clean the punctuation, find the 10 most frequent words, and write the results to a report file.
The school writing club wants to make a short "identity card" for each story it publishes in its magazine: how many words does the story have, which words appear most, how long are the sentences? Counting by hand takes hours; you will write a program that does it. The sample text is story.txt: the story of Maya, who waits for the last ferry on the pier of a harbor town (about 165 lines).
At the end, your program will write this report to the file report.txt:
OutputTEXT REPORT: Last Ferry
------------------------------
Lines: 166 (non-empty: 151)
Words: 1475 (different: 458)
Sentences: 150
Average word length: 4.09
Longest word: hafenstrasse
Most frequent words:
maya: 31
ferry: 19
...On the way you will meet a trap: lower() only changes the case of letters, so it turns HAFENSTRASSE into hafenstrasse but leaves Hafenstraße as hafenstraße; the two spellings of the street name are counted as different words. If you do not fix this, the table of the most frequent words will be wrong.
Lessons used: functions and return (14), string methods strip, split, replace, lower (21), formatting (22), lists and enumerate (23–24), counting with Counter and looping over a dictionary (27, 37), sets (29), comprehensions (30), max and key, lambda (31), reading and writing a text file (33), import (36).
How to work: The seven cells share one session: the text and lines you read in the first cell, and the split_words function you write in the 3rd cell, are used in the later cells. The comments tell you what to do, and you write the code where it says ___. Run the cell, compare your output with the "Show expected output" box, then press Check. Do not type the results by hand; the checks also try your functions on other texts.
What you'll do
story.txtDownload file
Reading file…
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
The story is in story.txt. The first line is the title, and there is one empty line between paragraphs. Open the file with encoding="utf-8" so accented letters are read correctly, and read the whole text at once into the name text.
Then split the text into lines. The file ends with a line break, so split("\n") on its own adds an empty line at the end; first remove the whitespace at the start and end of the text with strip(), then split. Finally, put the lines that are not empty into a separate list: an empty line is one that is "" after strip().
This step's code cell is for members.Sign up free
When you count words, Straße and STRASSE must count as the same word, so you will convert everything to lowercase. But lower() only changes the case of letters, and in German-based words it misses one thing: the letter
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
ßss"STRASSE".lower() gives "strasse", but "Straße".lower() stays "straße". The two are not equal, so they would be counted as two different words."ß".upper() is two characters, "SS": one letter becomes two.The fix is a string method made for comparing text without caring about case: casefold(). It turns ß into ss, and it keeps accents: "CAFÉ".casefold() is "café". Use casefold() instead of lower() everywhere you compare words.
This step's code cell is for members.Sign up free
Now you will split the text into words. split() alone is not enough: dear, and dear would count as two different words. split_words(text) should do three things:
1. Convert the text to lowercase with fold_case.
2. Replace every mark in PUNCTUATION with a space (loop over the marks with a for loop).
3. Split on spaces and keep only the part of each word before the apostrophe ('): Maya's → maya, Marco's → marco. A possessive ending is attached with an apostrophe, and we drop it so that we count the base word.
The function returns the list of words. The lines below the cell put all the words of the story into the name words; the next steps use this list.
This step's code cell is for members.Sign up free
Which words appear most in the story? First remove the stop words: words like "the", "a" and "and" that appear a lot in every text but say nothing about this one. The list is ready in the STOPWORDS set. Count the rest with Counter and take the 10 most frequent words.
This table tests the previous two steps. If Hafenstraße, Hafenstrasse and HAFENSTRASSE are not merged correctly, the counts in the top 10 change, and some words even drop out of the list.
This step's code cell is for members.Sign up free
Three more numbers tell you about the writer's word choice:
average_length: the average number of letters of all the words (stop words included), rounded to 2 decimal places.longest_word: the word with the most letters. If there is a tie, the word that comes first in the story stays; max already does this.appears_once: the number of different words that appear only once in the story. Count all of words (stop words included) again for this.This step's code cell is for members.Sign up free
To find the sentences, split at the sentence-ending marks. split_sentences(text) should do the following:
1. Turn the line breaks ("\n") into spaces: a sentence may run over two lines.
2. Replace ! and ? with ., so that you only need to split at one mark.
3. Split at ., clean each part with strip(), and drop the parts that are empty (after the last full stop of the text, an empty part is left).
The title line has no full stop at the end, so that it is not counted as a sentence, the cell separates the first line and works with the rest, body. At the end, find the sentence with the most words: the word count comes from the split_words function of step 3.
This step's code cell is for members.Sign up free
Write all the results to the file report.txt. Most of the report lines are ready in the report list; you will add the lines for the 10 most frequent words (two spaces, the word, a colon, the count: maya: 31).
Then open the file in write mode ("w") and write each line with "\n" at the end: write does not add the line break itself. Finally, read the file back and print it; what you see on the screen should be exactly what is in the file.
This step's code cell is for members.Sign up free