Загрузка данных


from docx import Document
from pathlib import Path

REPLACEMENTS = {
    "Иванов Иван Иванович": "[ФИО]",
    "ООО Ромашка": "[ОРГАНИЗАЦИЯ]",
    "+7 999 123-45-67": "[ТЕЛЕФОН]",
    "test@mail.ru": "[EMAIL]"
}


def replace_in_paragraph(paragraph, replacements):
    full_text = ''.join(run.text for run in paragraph.runs)

    new_text = full_text
    for old, new in replacements.items():
        new_text = new_text.replace(old, new)

    if new_text == full_text:
        return

    # сохраняем форматирование первого run
    first_run = paragraph.runs[0] if paragraph.runs else None

    # удаляем текст из всех runs
    for run in paragraph.runs:
        run.text = ""

    if first_run:
        first_run.text = new_text


def process_doc(doc):
    # Абзацы
    for paragraph in doc.paragraphs:
        replace_in_paragraph(paragraph, REPLACEMENTS)

    # Таблицы
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    replace_in_paragraph(paragraph, REPLACEMENTS)


folder = Path(__file__).parent

for file in folder.glob("*.docx"):

    if file.stem.endswith("_anon"):
        continue

    print(f"Обработка: {file.name}")

    doc = Document(file)

    process_doc(doc)

    output = file.with_name(file.stem + "_anon.docx")
    doc.save(output)

print("Готово.")