Course 4.1Lesson 2 of 5
Real text is messy: The, the and THE are three different strings, and a word with a full stop is not the same as the word without. Before counting, clean the text in the same steps: make every letter small with lower, remove the punctuation with replace, cut the text into words with split, and then count with a dictionary or ask a question about the list. The key of the dictionary is the word and the value is how many times it was seen. max with key equals len gives the longest word, and max with key equals counts.get gives the most common word. A list comprehension can pick out the letters that pass a test.
Try the code and the simulations beside the lesson.
After this lesson you can
The words The, the and THE are the same word, but Python sees three different strings. A word with a full stop, cat., is not the same as cat. So before we count, we clean.
The steps are always the same:
Predict first. After cleaning, how many words does the text have? Which word is the longest, and how many words have exactly 3 letters? Then run it.
The cleaned text has 10 words. The longest word is kitten, with 6 letters, and 7 words have 3 letters: the three times, and sat, ran, did and nap.
You counted letters with a dictionary in the first course of this book. Counting words is the same idea: the key is a word, and the value is how many times we saw it.
Most of the shortest words carry little meaning. Leaving them out is a first step to finding what a text is about.
The cleaning above handles a simple text. Real texts have more trouble.
don't becomes dont if you remove all the marks, and it's becomes its. For a count, that is often fine. For a careful job, keep the apostrophe.well-known is one word or two? Decide, and be consistent.letter.isalpha() or it is a space. This removes every kind of mark without a list. You will use it in the project.The and the are two words.replace(".", "") on "end.Start" gives endStart. Replace the mark by a space if words can touch it.max(words) without a key gives the last word alphabetically.lower(). Write tidy = text.lower().len(text)) when you mean the number of words (len(words)).Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
lower(), then replace() for every punctuation mark.split() for the words, and a dictionary to count them.max(words, key=len) is the longest word. max(counts, key=counts.get) is the most common.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
max(["to", "be", "kitten"], key=len) give?counts.get(word, 0) give the first time a word is seen?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.