1.1 A function that counts
just setupA word counter needs a way to count. A function, count, takes a text and gives a dictionary from each word to how
many times it appears. It goes in src/tally/__init__.py, above main. The command does not use it yet.
A patch to src/tally/__init__.py.
In src/tally/__init__.py, count now stands above main. It splits the text at every space, tab and end of line. For each word, it
adds 1 to the count so far, and counts.get(word, 0) gives 0 for a word it has not seen.
uv run python -c "from tally import count; print(count('a b a'))"It prints {'a': 2, 'b': 1}, two of a and one of b. So the function works, though the command still has
nothing to count.
What changed
src/tally/__init__.py: a dictionary from each word to how many times it appears. 7 lines added. The file.- look at
counts[word] = counts.get(word, 0) + 1
- look at
The diff of src/tally/__init__.py
@@ -1,5 +1,12 @@
"""tally: count the words in a text."""
+def count(text):
+ counts = {}
+ for word in text.split():
+ counts[word] = counts.get(word, 0) + 1
+ return counts
+
+
def main() -> None:
print("tally: nothing to count yet")