1 Counting

just setup

A word counter must count. A function, count, splits a text into words and counts each one. main reads a file, or the standard input when you give no file, and prints each word with its count.

echo "a b a" | uv run tally
echo "The the THE" | uv run tally

The first command prints 2 a and 1 b. The second prints three lines, 1 THE, 1 The and 1 the. tally counts each as a different word, because it does not know yet that case does not matter. The second slide is a picture of what count does.

Ask: is that a bug, and who decides?

What changed

  • src/tally/__init__.py: count, and a main that reads the text and prints the counts. 12 lines added, 1 removed. The file.
    • look at counts[word] = counts.get(word, 0) + 1
The diff of src/tally/__init__.py
@@ -1,5 +1,16 @@
 """tally: count the words in a text."""
 
+import sys
+
+
+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")
+    text = open(sys.argv[1]).read() if len(sys.argv) > 1 else sys.stdin.read()
+    for word, n in sorted(count(text).items()):
+        print(n, word)

This change on GitHub. The code after it.