#!/usr/bin/env python3 """Извлечение текста из DOCX.""" from __future__ import annotations import argparse import sys from pathlib import Path from docx import Document from docx.table import Table from docx.text.paragraph import Paragraph def iter_blocks(document: Document): for child in document.element.body.iterchildren(): if child.tag.endswith("}p"): yield Paragraph(child, document) elif child.tag.endswith("}tbl"): yield Table(child, document) def main() -> int: parser = argparse.ArgumentParser(description="Извлечь текст из DOCX") parser.add_argument("input", type=Path, help="Исходный DOCX") parser.add_argument("--include-tables", action="store_true", help="Добавить содержимое таблиц") parser.add_argument("--outdir", type=Path, default=Path("text"), help="Папка результатов") parser.add_argument("--force", action="store_true", help="Перезаписать результат") args = parser.parse_args() path = args.input.expanduser() if not path.is_file(): print(f"Файл не найден: {path}", file=sys.stderr) return 2 if path.suffix.lower() not in {".docx", ".docm"}: print("Поддерживаются файлы .docx и .docm", file=sys.stderr) return 2 target = args.outdir.expanduser() / f"{path.stem}.txt" if target.exists() and not args.force: print(f"Файл уже существует: {target}. Добавьте --force.", file=sys.stderr) return 2 try: document = Document(str(path)) except Exception as error: print(f"Не удалось открыть DOCX: {error}", file=sys.stderr) return 1 parts: list[str] = [] for block in iter_blocks(document): if isinstance(block, Paragraph): text = block.text.strip() if text: parts.append(text) elif args.include_tables: for row in block.rows: cells = [" ".join(cell.text.split()) for cell in row.cells] if any(cells): parts.append(" | ".join(cells)) content = "\n".join(parts) + "\n" target.parent.mkdir(parents=True, exist_ok=True) target.write_text(content, encoding="utf-8") print(f"Готово: {target}, символов: {len(content)}") return 0 if __name__ == "__main__": raise SystemExit(main())