#!/usr/bin/env python3 """Статистика текста: строки, слова, символы, предложения.""" from __future__ import annotations import argparse import json import re from pathlib import Path WORD = re.compile(r"[^\W\d_]+(?:['-][^\W\d_]+)*", re.UNICODE) SENTENCE_END = re.compile(r"[.!?]+") def text_stats(text: str) -> dict[str, int]: words = WORD.findall(text) characters = len(text) characters_no_spaces = len(re.sub(r"\s", "", text)) sentences = len(SENTENCE_END.findall(text)) paragraphs = len([part for part in re.split(r"\n\s*\n", text) if part.strip()]) return { "lines": len(text.splitlines()), "words": len(words), "characters": characters, "characters_no_spaces": characters_no_spaces, "sentences": sentences, "paragraphs": paragraphs, "reading_minutes": (len(words) + 199) // 200, } def collect(path: Path, pattern: str) -> list[Path]: if path.is_file(): return [path] return sorted(item for item in path.rglob(pattern) if item.is_file()) def main() -> int: parser = argparse.ArgumentParser(description="Подсчитать слова и символы") parser.add_argument("paths", nargs="+", type=Path, help="Файлы или папки") parser.add_argument("--glob", default="*.txt", help="Маска при обходе папки") parser.add_argument("--encoding", default="utf-8", help="Кодировка") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() reports = [] for path in args.paths: root = path.expanduser() if not root.exists(): print(f"Пропуск: {root} не найден") continue for item in collect(root, args.glob): try: text = item.read_text(encoding=args.encoding) except (UnicodeDecodeError, OSError) as error: print(f"Пропуск {item}: {error}") continue stats = text_stats(text) stats["file"] = str(item) reports.append(stats) if not reports: print("Файлы не найдены") return 1 print(f"{'Файл':40} {'Строк':>7} {'Слов':>7} {'Симв.':>8} {'Без проб.':>9} {'Предл.':>7} {'Абз.':>5} {'Мин':>4}") for row in reports: name = Path(row["file"]).name[:40] print(f"{name:40} {row['lines']:>7} {row['words']:>7} {row['characters']:>8} {row['characters_no_spaces']:>9} {row['sentences']:>7} {row['paragraphs']:>5} {row['reading_minutes']:>4}") total_words = sum(row["words"] for row in reports) print(f"Всего файлов: {len(reports)}, слов: {total_words}") if args.json: args.json.expanduser().write_text( json.dumps({"files": reports, "total_words": total_words}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Отчёт: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())