File size: 1,058 Bytes
b4f2238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""Business logic services."""

import logging
import re

logger = logging.getLogger(__name__)


PLACEHOLDER_PATTERN = re.compile(r"\{\{\s*([\w\u4e00-\u9fff][\w\u4e00-\u9fff\.\(\)]*)\s*\}\}")


def extract_placeholders(file_path: str) -> list[str]:
    placeholders: set[str] = set()

    try:
        from docxtpl import DocxTemplate

        doc = DocxTemplate(file_path)
        undeclared = doc.get_undeclared_template_variables()
        placeholders.update(undeclared)
    except Exception:
        logger.exception("操作失败")

        pass

    try:
        from docx import Document

        word_doc = Document(file_path)
        for para in word_doc.paragraphs:
            placeholders.update(PLACEHOLDER_PATTERN.findall(para.text))

        for table in word_doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    placeholders.update(PLACEHOLDER_PATTERN.findall(cell.text))
    except Exception:
        logger.exception("操作失败")

        pass

    return sorted(list(placeholders))