117 lines
4.8 KiB
Python
117 lines
4.8 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Перенос пользовательского слоя словаря (*.local.txt с целевого компа) в репозиторий.
|
||
|
||
Кнопка «В словарь» пишет в exceptions.local.txt / toponyms.local.txt рядом с
|
||
комплектом (переживает update кода). Периодически накопленное переносят в
|
||
tracked-словарь этим скриптом — вручную, не автоматически:
|
||
|
||
python3 scripts/dict_promote.py [путь/*.local.txt ...] [--apply]
|
||
|
||
Без --apply — только показать накопленное и предложения. Топонимы-прилагательные
|
||
выдаются готовыми стемами для ADJ_STEMS (scripts/gen_toponyms.py); файл-генератор
|
||
правится руками (скилл: toponyms.txt руками не править), скрипт его не трогает.
|
||
"""
|
||
import os
|
||
import re
|
||
import sys
|
||
|
||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
# прилагательные-топонимы: стем = форма минус окончание (стем минус «ский», не «ий»)
|
||
_ADJ_CUTS = {
|
||
"ского": 5, "скими": 5, "скому": 5,
|
||
"ский": 4, "ским": 4, "ском": 4,
|
||
"ская": 4, "ской": 4, "ское": 4,
|
||
"ские": 4, "ских": 4,
|
||
}
|
||
|
||
|
||
def parse_local(path):
|
||
"""[(слово, провенанс)] из *.local.txt; дубли игнорируются."""
|
||
seen = {}
|
||
try:
|
||
with open(path, encoding="utf-8") as fh:
|
||
for raw in fh:
|
||
line = raw.strip()
|
||
if not line or line.startswith("#"):
|
||
continue
|
||
parts = re.split(r"\s#\s?", line, maxsplit=1)
|
||
word = parts[0].strip()
|
||
if not word:
|
||
continue
|
||
key = word.lower()
|
||
if key not in seen:
|
||
seen[key] = (word, parts[1].strip() if len(parts) > 1 else "")
|
||
except OSError as e:
|
||
sys.exit(f"не читается {path}: {e}")
|
||
return list(seen.values())
|
||
|
||
|
||
def top_stems(words):
|
||
"""Стемы прилагательных-топонимов для ADJ_STEMS; остальное — как есть."""
|
||
stems, plain = set(), []
|
||
for w, _prov in words:
|
||
low = w.lower()
|
||
for suffix, cut in sorted(_ADJ_CUTS.items(), key=lambda kv: -len(kv[0])):
|
||
if low.endswith(suffix) and len(w) > cut + 2:
|
||
stems.add(w[:-cut])
|
||
break
|
||
else:
|
||
plain.append(w)
|
||
return sorted(stems), plain
|
||
|
||
|
||
def main():
|
||
args = sys.argv[1:]
|
||
apply = "--apply" in args
|
||
paths = [a for a in args if not a.startswith("--")]
|
||
if not paths:
|
||
for name in ("exceptions.local.txt", "toponyms.local.txt"):
|
||
for d in (ROOT, os.getcwd()):
|
||
p = os.path.join(d, name)
|
||
if os.path.exists(p):
|
||
paths.append(p)
|
||
if not paths:
|
||
print("*.local.txt не найдены (поиск: корень репо + cwd)")
|
||
print("указание: скопируйте файлы с целевого компа и запустите с путями")
|
||
return
|
||
|
||
all_words = []
|
||
for p in paths:
|
||
items = parse_local(p)
|
||
print(f"\n== {p}: {len(items)} слов(форм) ==")
|
||
for w, prov in items:
|
||
print(f" {w}" + (f" # {prov}" if prov else ""))
|
||
all_words.extend(items)
|
||
|
||
exc_words, top_words = [], []
|
||
for p in paths:
|
||
items = parse_local(p)
|
||
base = os.path.basename(p)
|
||
if base.startswith("exceptions"):
|
||
exc_words.extend(items)
|
||
else:
|
||
top_words.extend(items)
|
||
|
||
print("\n=== предложения ===")
|
||
if exc_words:
|
||
uniq = sorted({w for w, _ in exc_words})
|
||
print(f"в exceptions.txt: {len(uniq)} уникальных")
|
||
if apply:
|
||
with open(os.path.join(ROOT, "exceptions.txt"), "a", encoding="utf-8") as fh:
|
||
fh.write("\n# — перенос с целевого компа (scripts/dict_promote.py)\n")
|
||
fh.write("\n".join(uniq) + "\n")
|
||
print(" -> дописано в exceptions.txt")
|
||
if top_words:
|
||
stems, plain = top_stems(top_words)
|
||
if stems:
|
||
print(f"стемы для ADJ_STEMS (scripts/gen_toponyms.py): {', '.join(stems)}")
|
||
if plain:
|
||
print(f"не-прилагательные (переносить вручную): {', '.join(plain)}")
|
||
if apply and stems:
|
||
print(" (toponyms.txt не пишется автоматически: правятся данные генератора)")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|