Paul's Python CoursePPC

Project 4 of 20, for Aaesha

Word Counter and Text Analyser

Count every word in a real book for Aaesha's reading experiment, report the ten it uses most, and save every count to a file a spreadsheet can open.

About an hour and a half, in 15 steps.

Sign up free to open itLog in

Act 2 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaI'm setting up a reading experiment, because people read a common word faster than a rare one.
  • AaeshaI need to know which words Alice in Wonderland uses most, and I'd started counting them by hand.
  • AaeshaThen I saw how long the book actually is.
  • AaeshaI'd like every word once with how many times it's used, one row each and never two.
  • PaulYou'll read the file in and write the counts back out, and the counting in between is honestly the easy bit.

Aaesha's copy of the book is alice.txt. Write words.py:

  1. read_words(path) returns every word in the file, in order. A word is a piece of what split() gives, with any punctuation (string.punctuation) stripped from both ends, in lower case. A piece with nothing left isn't a word.
  2. top_words(words, count=10) returns the count commonest words as (word, times) pairs, commonest first, leaving out every word in SMALL_WORDS. Words with the same count stay in the order they first turned up.
  3. save_counts(words, path) writes a CSV file: the header word,times, then a row for every different word, commonest first.
  4. main() asks Which book? , prints the report and saves every count in counts.csv. If there's no such file, it says There's no book called alice.text. and stops. A file with no words in it gets empty.txt has no words in it.
What it prints
Which book? alice.txt
Words: 26,628
Different words: 2,669
Most common, leaving out the small words:
1. said: 462
2. alice: 386
3. little: 129
4. down: 103
5. know: 87
6. like: 85
7. went: 83
8. again: 83
9. thought: 74
10. time: 68
Every count is in counts.csv.

What you learn

What's in it

  1. Reading a file
  2. The book as it is
  3. Writing a file
  4. Writing it down
  5. Counting for you
  6. Somebody else's tally
  7. A file a spreadsheet can open
  8. A comma in the value
  9. Is the file there
  10. Before you open it
  11. How Paul would do it
  12. Fix Riya's version
  13. Make the word counter
  14. Ship it