#!/usr/bin/env python3 """Фильтрация CSV по набору условий.""" from __future__ import annotations import argparse import csv import re from pathlib import Path OPERATORS = ("!=", ">=", "<=", "=", ">", "<", "~") def parse_condition(text: str) -> tuple[str, str, str]: for operator in OPERATORS: index = text.find(operator) if index > 0: column = text[:index].strip() value = text[index + len(operator):].strip() if not column: break return column, operator, value raise ValueError(f"Неверное условие: {text}") def matches(value: str, operator: str, expected: str, regex: re.Pattern[str] | None, ignore_case: bool) -> bool: left = value.strip() right = expected.strip() if ignore_case: left_cmp = left.casefold() right_cmp = right.casefold() else: left_cmp = left right_cmp = right if operator in {">", ">=", "<", "<="}: try: first = float(left.replace(",", ".")) second = float(right.replace(",", ".")) except ValueError: return False if operator == ">": return first > second if operator == ">=": return first >= second if operator == "<": return first < second return first <= second if operator == "=": return left_cmp == right_cmp if operator == "!=": return left_cmp != right_cmp if operator == "~": return bool(regex and regex.search(left)) return False def main() -> int: parser = argparse.ArgumentParser(description="Фильтрация CSV") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--output", type=Path, default=Path("filtered.csv"), help="Результат") parser.add_argument("--where", action="append", required=True, help="Условие, можно повторять") parser.add_argument("--ignore-case", action="store_true", help="Не учитывать регистр") parser.add_argument("--limit", type=int, default=0, help="Максимум строк в результате") parser.add_argument("--delimiter", default=",", help="Разделитель колонок") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.input.expanduser().resolve() target = args.output.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if source == target: parser.error("Выходной файл не должен совпадать с исходным") if target.exists() and not args.force: parser.error(f"Файл уже существует: {target}. Добавьте --force") if len(args.delimiter) != 1: parser.error("Разделитель должен состоять из одного символа") conditions = [] try: for text in args.where: column, operator, expected = parse_condition(text) flags = re.IGNORECASE if args.ignore_case else 0 regex = re.compile(expected, flags) if operator == "~" else None conditions.append((column, operator, expected, regex)) except (ValueError, re.error) as error: parser.error(str(error)) with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle, delimiter=args.delimiter) if reader.fieldnames is None: parser.error("Не удалось прочитать заголовок") missing = [column for column, _, _, _ in conditions if column not in reader.fieldnames] if missing: parser.error("Нет колонок: " + ", ".join(sorted(set(missing)))) selected = [] total = 0 for row in reader: total += 1 if all(matches(row.get(column, ""), operator, expected, regex, args.ignore_case) for column, operator, expected, regex in conditions): selected.append(row) if args.limit and len(selected) >= args.limit: break with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=reader.fieldnames, delimiter=args.delimiter, lineterminator="\n") writer.writeheader() writer.writerows(selected) print(f"Проверено строк: {total}") print(f"Подошло строк: {len(selected)}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())