#!/usr/bin/env python3 """Сортировка строк текстового файла.""" from __future__ import annotations import argparse import re import shutil from pathlib import Path NUMBER = re.compile(r"[-+]?\d+(?:[.,]\d+)?") def natural_key(text: str) -> list[tuple[int, object]]: parts = re.split(r"(\d+)", text) key: list[tuple[int, object]] = [] for part in parts: 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) if not match: return float("inf") return float(match.group(0).replace(",", ".")) def make_key(args: argparse.Namespace): if args.numeric: return numeric_key if args.natural: return natural_key def text_key(line: str) -> str: return line.casefold() if args.ignore_case else line return text_key def main() -> int: parser = argparse.ArgumentParser(description="Отсортировать строки файла") parser.add_argument("--input", type=Path, required=True, help="Входной файл") parser.add_argument("--output", type=Path, help="Выходной файл, по умолчанию stdout") 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("--in-place", action="store_true", help="Заменить исходный файл") args = parser.parse_args() if args.numeric and args.natural: parser.error("Выберите что-то одно: --numeric или --natural") source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.in_place and args.output: parser.error("С --in-place не указывайте --output") if args.output and args.output.expanduser().resolve() == source.resolve(): parser.error("Выходной файл совпадает с входным, используйте --in-place") lines = source.read_text(encoding=args.encoding).splitlines() key = make_key(args) lines.sort(key=key, reverse=args.reverse) result = "\n".join(lines) + ("\n" if lines else "") if args.in_place: backup = source.with_name(source.name + ".bak") shutil.copy2(source, backup) source.write_text(result, encoding=args.encoding) print(f"Отсортировано строк: {len(lines)}, копия: {backup.name}") elif args.output: target = args.output.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(result, encoding=args.encoding) print(f"Отсортировано строк: {len(lines)}, результат: {target}") else: print(result, end="") return 0 if __name__ == "__main__": raise SystemExit(main())