-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworddict.py
More file actions
63 lines (51 loc) · 2.19 KB
/
Copy pathworddict.py
File metadata and controls
63 lines (51 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""Build a simple HTML dictionary from ``word=definition`` lines.
Usage: python3.14 worddict.py INPUT [--number]
The result is written to ``wordlist.html`` next to the input file.
"""
from __future__ import annotations
import argparse
import html
import sys
from collections.abc import Iterable
from pathlib import Path
WordGroups = dict[str, list[list[str]]]
def process_words(lines: Iterable[str]) -> WordGroups:
"""Deduplicate, parse, and group non-empty word-list lines."""
words = {line.strip() for line in lines if line.strip()}
groups: WordGroups = {}
for word in words:
groups.setdefault(word[0].upper(), []).append(word.split("="))
for entries in groups.values():
entries.sort(key=lambda entry: entry[0].casefold())
return groups
def render_html(groups: WordGroups, *, numbered: bool = False) -> str:
"""Render grouped words as an HTML fragment."""
output: list[str] = []
number = 1
for letter in sorted(groups):
output.append(f"<h2>{html.escape(letter)}</h2>")
for parts in groups[letter]:
text = " — ".join(html.escape(part) for part in parts)
prefix = f"{number}. " if numbered else ""
output.append(f"<p>{prefix}{text}</p>")
number += 1
return "\n".join(output) + "\n"
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Build an HTML dictionary from a word list.")
parser.add_argument("file", type=Path, help="UTF-8 word-list file")
parser.add_argument("--number", action="store_true", help="number entries")
args = parser.parse_args(argv)
if not args.file.is_file():
parser.error(f"file not found: {args.file}")
try:
groups = process_words(args.file.read_text(encoding="utf-8").splitlines())
output = args.file.parent / "wordlist.html"
output.write_text(render_html(groups, numbered=args.number), encoding="utf-8")
except OSError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
print(f"Processed words: {sum(len(entries) for entries in groups.values())}")
print(f"Written: {output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())