dkl9 commited on 2025-202 23:17:21
Showing 1 changed files, with 25 additions and 19 deletions.
| ... | ... |
@@ -1,25 +1,15 @@ |
| 1 |
+#!/usr/bin/python3 |
|
| 2 |
+import argparse |
|
| 1 | 3 |
from collections import defaultdict |
| 2 | 4 |
import re |
| 3 | 5 |
import sys |
| 4 | 6 |
import time |
| 5 | 7 |
from typing import Generator |
| 6 | 8 |
|
| 7 |
-def minima(options, key): |
|
| 8 |
- min_val = None |
|
| 9 |
- result = set() |
|
| 10 |
- for o in options: |
|
| 11 |
- k = key(o) |
|
| 12 |
- if min_val is None or k < min_val: |
|
| 13 |
- min_val = k |
|
| 14 |
- result = {o}
|
|
| 15 |
- elif k == min_val: |
|
| 16 |
- result.add(o) |
|
| 17 |
- return result |
|
| 18 |
- |
|
| 19 | 9 |
def cost(token_child: tuple[str, "Trie"]) -> tuple: |
| 20 | 10 |
token, child = token_child |
| 21 | 11 |
weight = child.deep_weight |
| 22 |
- return child.deep_usage / weight, -weight, child.min_depth, len(token), token |
|
| 12 |
+ return child.deep_usage / weight, child.min_depth, len(token), token |
|
| 23 | 13 |
|
| 24 | 14 |
class Trie: |
| 25 | 15 |
def __init__(self, weight: int = 0): |
| ... | ... |
@@ -73,13 +63,29 @@ class Trie: |
| 73 | 63 |
yield tokens |
| 74 | 64 |
self.use(tokens) |
| 75 | 65 |
|
| 66 |
+if __name__ == "__main__": |
|
| 67 |
+ parser = argparse.ArgumentParser(prog="dost", description="Diverse-order sampling by trie") |
|
| 68 |
+ parser.add_argument("files", default="-", nargs="*")
|
|
| 69 |
+ parser.add_argument( |
|
| 70 |
+ "-s", "--separators", default=" \t", |
|
| 71 |
+ help="characters that separate tokens in an input item (default space and tab)" |
|
| 72 |
+ ) |
|
| 73 |
+ parser.add_argument( |
|
| 74 |
+ "-t", "--token", |
|
| 75 |
+ help="structural regexp for a token of an input item, overrides -s" |
|
| 76 |
+ ) |
|
| 77 |
+ args = parser.parse_args() |
|
| 76 | 78 |
re_flags = re.MULTILINE | re.DOTALL |
| 77 |
-token_pattern = "[-_ \t]*[^-_\\s]+" |
|
| 79 |
+ if args.token: |
|
| 80 |
+ token_pattern = args.token |
|
| 81 |
+ else: |
|
| 82 |
+ token_pattern = f"[{args.separators}]*[^{args.separators}\r\n]+"
|
|
| 78 | 83 |
entry_pattern = re.compile(f"({token_pattern})+", re_flags)
|
| 79 | 84 |
token_pattern = re.compile(token_pattern, re_flags) |
| 80 |
-words = [re.findall(token_pattern, m.group(0)) for m in re.finditer(entry_pattern, sys.stdin.read())] |
|
| 81 | 85 |
t = Trie() |
| 82 |
-for w in words: |
|
| 83 |
- t.add(w) |
|
| 84 |
-for w in t.traverse(): |
|
| 85 |
- print("".join(w))
|
|
| 86 |
+ for filename in args.files: |
|
| 87 |
+ with sys.stdin if filename == "-" else open(filename, "r") as handle: |
|
| 88 |
+ for word in re.finditer(entry_pattern, handle.read()): |
|
| 89 |
+ t.add(re.findall(token_pattern, word.group(0))) |
|
| 90 |
+ for word in t.traverse(): |
|
| 91 |
+ print("".join(word))
|
|
| 86 | 92 |