5.2 tally --top N

just setup

tally prints every word of a text, and the corpus fills the screen. An option, --top N, makes main print only the N most common words, with top. Without the option, main prints every count, as before. main reads the option before the name of the file, so the command is tally --top 3 data/corpus.txt.

A patch to src/tally/__init__.py.

In src/tally/__init__.py, main now has a docstring, and the three lines under the docstring read the option. When the first argument is --top, the second is the number N, and the name of the file comes after them. The loop prints top(counts, n) when there is an N, and every count when there is not.

uv run tally --top 3 data/corpus.txt

The command prints three lines, the most common word first. They are 127 line, 126 class and 125 word.

What changed

  • src/tally/__init__.py: main reads the option before the name of the file. 8 lines added, 3 removed. The file.
    • look at if args[:1] == ["--top"]:
The diff of src/tally/__init__.py
@@ -17,6 +17,11 @@ def top(counts: dict[str, int], n: int) -> list[tuple[str, int]]:
 
 
 def main() -> None:
-    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)
+    "Count the words of a file, or of the standard input. With --top N, only the N most common."
+    args, n = sys.argv[1:], None
+    if args[:1] == ["--top"]:
+        n, args = int(args[1]), args[2:]
+    text = open(args[0]).read() if args else sys.stdin.read()
+    counts = count(text)
+    for word, times in top(counts, n) if n else sorted(counts.items()):
+        print(times, word)

This change on GitHub. The code after it.