PythonLesson 16 of 16
Final project: text statistics in Python
Time to put it all together. You'll write a program that reads a coffee shop review and finds out which words it uses most.
Key points
- lower() and replace() tidy the text, split() cuts it into words
- A dictionary makes a great counter: counts[word] = counts.get(word, 0) + 1
- sorted(..., key=function) sorts by whatever the function returns
- The minus before count puts big numbers first; the word breaks ties
- top[:3] is a slice with the first three pairs
Example
text = "Hello, hello world!"clean = text.lower().replace(",", "").replace("!", "")words = clean.split()print(words) counts = {}for word in words: counts[word] = counts.get(word, 0) + 1print(counts)Punctuation is gone, every word is lowercase, and the dictionary counted each one. hello shows up twice even though one had a capital letter.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Finish the program: count_words must return a dictionary of each word and how many times it appears, and at the end print the three most frequent words like coffee: 3.
Output
What your program prints appears here.