#!/usr/bin/env python3 """Извлечение адресов email из текстовых файлов.""" from __future__ import annotations import argparse import csv import re from collections import Counter from pathlib import Path EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}") SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv"} def collect(root: Path, pattern: str) -> list[Path]: if root.is_file(): return [root] files = [] for path in sorted(root.rglob(pattern)): if not path.is_file(): continue if any(part in SKIP_DIRS for part in path.parts): continue files.append(path) return files def main() -> int: parser = argparse.ArgumentParser(description="Извлечь адреса email") parser.add_argument("--path", type=Path, required=True, help="Файл или папка") parser.add_argument("--glob", default="*", help="Маска файлов") parser.add_argument("--encoding", default="utf-8", help="Кодировка") parser.add_argument("--csv", type=Path, help="Сохранить список в CSV") parser.add_argument("--domains", action="store_true", help="Показать статистику по доменам") args = parser.parse_args() root = args.path.expanduser() if not root.exists(): parser.error(f"Путь не найден: {root}") sources = collect(root, args.glob) if args.csv: csv_target = args.csv.expanduser().resolve() if csv_target in {path.resolve() for path in sources}: parser.error("CSV не должен совпадать с входным файлом") found: set[str] = set() for path in sources: try: text = path.read_text(encoding=args.encoding) except (UnicodeDecodeError, OSError) as error: print(f"Пропуск {path}: {error}") continue found.update(match.group(0).lower() for match in EMAIL.finditer(text)) if not found: print("Адреса не найдены") return 1 ordered = sorted(found) if args.domains: counts = Counter(address.split("@", 1)[1] for address in ordered) for domain, count in counts.most_common(): print(f"{count:>5} {domain}") else: for address in ordered: print(address) if args.csv: target = args.csv.expanduser() with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.writer(handle) writer.writerow(["email", "domain"]) for address in ordered: writer.writerow([address, address.split("@", 1)[1]]) print(f"Сохранено {len(ordered)} адресов в {target}") return 0 if __name__ == "__main__": raise SystemExit(main())