#!/usr/bin/env python3 """Слияние нескольких отсортированных текстовых файлов.""" from __future__ import annotations import argparse import heapq import re from pathlib import Path NUMBER = re.compile(r"[-+]?\d+(?:[.,]\d+)?") def natural_key(text: str) -> list[tuple[int, object]]: key: list[tuple[int, object]] = [] for part in re.split(r"(\d+)", text): if part.isdigit(): key.append((0, int(part))) elif part: key.append((1, part.casefold())) return key def numeric_key(text: str) -> float: match = NUMBER.search(text) return float(match.group(0).replace(",", ".")) if match else float("inf") def main() -> int: parser = argparse.ArgumentParser(description="Слить отсортированные файлы") parser.add_argument("files", nargs="+", type=Path, help="Отсортированные файлы") parser.add_argument("--output", type=Path, required=True, help="Куда записать результат") parser.add_argument("--encoding", default="utf-8", help="Кодировка") parser.add_argument("--ignore-case", action="store_true", help="Не учитывать регистр ключа") parser.add_argument("--numeric", action="store_true", help="Сортировать по первому числу") parser.add_argument("--natural", action="store_true", help="Естественная сортировка") parser.add_argument("--reverse", action="store_true", help="Обратный порядок") parser.add_argument("--unique", action="store_true", help="Убрать одинаковые строки") parser.add_argument("--skip-blank", action="store_true", help="Пропустить пустые строки") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() if args.numeric and args.natural: parser.error("Выберите что-то одно: --numeric или --natural") sources = [path.expanduser() for path in args.files] for source in sources: if not source.is_file(): parser.error(f"Файл не найден: {source}") output = args.output.expanduser() if output in sources: parser.error("Выходной файл не должен совпадать с входным") if output.exists() and not args.force: parser.error(f"Файл уже существует: {output}. Добавьте --force") if args.numeric: key = numeric_key elif args.natural: key = natural_key else: key = (lambda line: line.casefold()) if args.ignore_case else (lambda line: line) def lines(path: Path): for line in path.read_text(encoding=args.encoding).splitlines(): if args.skip_blank and not line.strip(): continue yield line merged = heapq.merge(*(lines(path) for path in sources), key=key, reverse=args.reverse) count = 0 seen = set() with output.open("w", encoding=args.encoding, newline="\n") as handle: for line in merged: marker = line.casefold() if args.ignore_case else line if args.unique and marker in seen: continue seen.add(marker) handle.write(line + "\n") count += 1 print(f"Записано строк: {count} в {output}") return 0 if __name__ == "__main__": raise SystemExit(main())