from pathlib import Path
DATA_RAW = Path("../data/raw")
text = (DATA_RAW / "the_star.txt").read_text(encoding="utf-8")
words = text.lower().split()
words[0:6]['twinkle,', 'twinkle,', 'little', 'star,', 'how', 'i']
In 010 we tried to count how many times “twinkle” appears in the rhyme and got zero, because the words in our list still had punctuation attached. To fix that, we need to clean every word in the list, and that takes a loop. In this tutorial you will write loops, choose what code runs with if and else, count words with a dictionary, and package your work into a function you can reuse. In the next tutorial you will use all of them to build the counting model from class in Python.
Much of this will be familiar, but still type and run all of the code as it is written here. The next tutorial builds on this code, and the checks GitHub runs when you push (see What to hand in) depend on it. When you have done that and the Your turn questions, try the ones under Going further too.
This week you will get your lab from GitHub. Follow Getting and handing in work with GitHub to join the course’s organization, accept this week’s assignment from its link on the schedule, clone the repository into your CSCI295 folder, open it in VS Code, and run uv sync. Then check in VS Code’s Explorer that the repository’s data/raw folder has the rhyme, the_star.txt, and a much longer text, alice.txt, which we will use in the next tutorial.
Make a notebook called repeating_and_deciding.ipynb in the notebooks folder, and choose the lab’s own Python as the kernel, as you did in 010 (Select Kernel › Python Environments…). VS Code may call it .venv or csci295-week02-counting-model (the name in the lab’s pyproject.toml), and it usually marks it Recommended. Check that its path is .venv/bin/python (.venv\Scripts\python.exe on Windows). Start the notebook with a Markdown cell with a title, and then read in the rhyme the way you did last week.
As in 010, type each piece of code on this page into your notebook, run it, and check that your output matches the page’s (see How to work through the tutorials).
from pathlib import Path
DATA_RAW = Path("../data/raw")
text = (DATA_RAW / "the_star.txt").read_text(encoding="utf-8")
words = text.lower().split()
words[0:6]['twinkle,', 'twinkle,', 'little', 'star,', 'how', 'i']
Save the notebook, and make your first commit and push it, as described in the GitHub guide’s Committing and pushing. Check on GitHub that it arrived, and then carry on here.
A for loop runs the same code once for each item in a list. Here is a loop that prints the first six words, one per line.
Read it as “for each word in the first six words, print the word.” Python is strict about three details here:
:.IndentationError.for (here word) is a variable. Each time through the loop, Python sets it to the next item in the list, so the body runs once with word equal to 'twinkle,', then again with 'twinkle,', then with 'little', and so on.The loop ends where the indenting ends. Compare these two cells, and predict how many lines each one prints before you run them. Then run them, and open Check your prediction below the cells to compare.
The first cell prints six lines:
twinkle,
---
twinkle,
---
little
---
The second cell prints four:
twinkle,
twinkle,
little
---
In the second cell, the last line is not indented, so it is not part of the loop. It runs once, after the loop is done.
Here is the count from 010 again. Run it in your new notebook:
In fact, all four times “twinkle” appears in the list, it is 'twinkle,' with a comma, and to Python 'twinkle,' and 'twinkle' are different strings.
The string method strip removes characters from the beginning and end of a string. We tell it which characters to remove, here the punctuation marks that appear in the rhyme.
To clean every word, we start with an empty list and use a loop to add each cleaned word to it with the list method append.
['twinkle', 'twinkle', 'little', 'star', 'how', 'i']
Now count again, using the clean list.
The count is now four. Notice that we did not change the original list. words still has the punctuation, because we made a new list, clean_words. We kept the original for the same reason we never edit the files in data/raw.
Often we want the code to do different things in different situations. An if statement runs its indented code only when a condition is True. Conditions are usually comparisons like the ones you met last week, such as 2 + 2 == 4, and they are either True or False.
twinkle <-- found one
twinkle <-- found one
little
star
how
i
wonder
what
The else part runs when the condition is False, and you can leave it out. Like for, both if and else end with a colon and have their own indented code. Here the if statement is inside the loop, so its code is indented twice.
Here are the comparisons you will use most often:
| Code | Means |
|---|---|
a == b |
a equals b |
a != b |
a does not equal b |
a < b, a > b |
less than, greater than |
a <= b, a >= b |
less than or equal to, greater than or equal to |
a in b |
a is an item in the list b, a piece of the string b, or a key of the dictionary b |
For example, which words in the rhyme are longer than five letters?
twinkle
twinkle
little
wonder
diamond
blazing
nothing
shines
little
twinkle
twinkle
And we can ask whether a word appears in the rhyme at all:
The count method answers the question for one word at a time. To count every word, we need somewhere to keep a running total for each one, so we will use a dictionary. It stores keys and a value for each key, like a word and its count. Dictionaries are written with curly braces, with a colon between each key and its value:
Square brackets look up the value for a key, and you can use them to add a key or change its value:
Now we can count every word in the rhyme, starting with an empty dictionary. For each word, if it is already a key, we add one to its count. If not, it is the first time we have seen the word, so its count starts at one.
counts = {}
for word in clean_words:
if word in counts:
counts[word] = counts[word] + 1
else:
counts[word] = 1
counts{'twinkle': 4,
'little': 2,
'star': 1,
'how': 1,
'i': 1,
'wonder': 1,
'what': 1,
'you': 2,
'are': 1,
'up': 1,
'above': 1,
'the': 4,
'world': 1,
'so': 1,
'high': 1,
'like': 1,
'a': 1,
'diamond': 1,
'in': 1,
'sky': 1,
'when': 2,
'blazing': 1,
'sun': 1,
'is': 1,
'gone': 1,
'he': 1,
'nothing': 1,
'shines': 1,
'upon': 1,
'then': 1,
'show': 1,
'your': 1,
'light': 1,
'all': 1,
'night': 1}
Take a minute to trace through the loop for the first few words by hand. What does counts look like after the first word? After the second? After the third? (A dictionary keeps its keys in the order they were first added, which is why the words come out in the order they first appear in the rhyme.)
The dictionary has one key for each different word:
So the rhyme has 44 words but only 35 different ones. And now we can look up any word:
What happens if you look up a word that is not a key, like counts["moon"]? Try it, and read the error message. (Then turn that line into a comment, so it does not stop Run All.)
We have cleaned the words of one text, and in the next tutorial we will want to do the same to a much longer one. Rather than copy the code, we can turn it into our own function. You have been using functions all along (len, print, and type), and now you will write one.
Nothing happens when you run this cell, because it only defines the function and does not run it. Here is what each part does:
def clean(text): says we are defining a function named clean that takes one input, which will be called text inside the function.return clean_words sends the finished list back to whoever called the function.The docstring is what Python shows when you ask for help with the function. Try it:
Help on function clean in module __main__:
clean(text)
Split text into lower-case words and strip punctuation from each one.
Now we can call the function on the rhyme, or on any text at all:
['curiouser', 'and', 'curiouser', 'cried', 'alice']
Inside clean, words was just set to the words of the Alice sentence. Did that change the words list at the top of the notebook? Predict what words[0] gives before you run it.
'twinkle,'
It has not changed. The variables inside a function belong to the function. Its words and clean_words are separate from the lists with those names at the top of the notebook.
Put your answers in your notebook after the tutorial code. Before each answer, add a Markdown cell with a heading that gives the question’s number and what it is about, such as ### 1. Words that start with t. Give each part of a question with parts (3a, 3b, and so on) its own heading. When a question asks you to explain something or to answer in words, write the answer in a Markdown cell, in full sentences, right after any code it is about.
help(str.startswith).) Then make your code count them, repeats included, instead of counting by hand.best_word = "" and best_count = 0. Inside the loop, when a word’s count is larger than best_count, update both. (Looping over a dictionary gives you its keys, as in for word in counts:.) Is there a tie? What does your loop do when there is one?clean_words = [] were inside the loop (indented) instead of before it? To find out, copy the cleaning loop into a new cell, change the name of the list to test_words everywhere in that cell (so that you do not change clean_words), and move test_words = [] inside the loop. Run it, look at test_words, and explain what happened.if line (it appends every stripped word). Then find a string for which the two functions give different results, and show both results.These are optional.
count_words that takes a list of words and returns a dictionary of counts. Check that count_words(clean_words) == counts is True.counts[word] = counts.get(word, 0) + 1. Look up the dictionary method get and explain why this line does the same job as our if and else.When you have finished, click Restart and then Run All. Check that everything runs and that the results still match the tutorial and your notes, and save. Then commit and push your work as described in the GitHub guide, so that you have a backup. You will keep working on this same lab in the next tutorial, and both of this week’s notebooks are handed in together by the week 2 deadline on the schedule.
Part of your grade comes from checks that GitHub runs on your work each time you push. The checks look at both of this week’s notebooks, this one and the one you will make in the next tutorial. For each notebook, they check that every cell was run in order and saved, that the notebook runs from top to bottom without an error, and that some of your results match the tutorial’s. To see how you did, open the Feedback pull request in your repository (the Pull requests tab) and click the link to the latest autograding result. A check that does not pass tells you what is wrong. Fix it, run the notebook again with Restart and Run All, and push. You can do that as many times as you need before the deadline. Until you have done the next tutorial, the checks for its notebook will not pass, and that is expected.