12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- """
- 检查模板文件中的变量
- """
- import os
- from docx import Document
- from utils.logger import logger
- def check_template_variables(template_path):
- """
- 检查模板文件中的所有变量
-
- 参数:
- template_path: 模板文件路径
-
- 返回:
- set: 找到的变量集合
- """
- logger.info(f"开始检查模板文件: {template_path}")
-
- if not os.path.exists(template_path):
- logger.error(f"模板文件不存在: {template_path}")
- return set()
-
- doc = Document(template_path)
-
- # 收集文档中的所有文本
- all_text = []
-
- # 检查段落中的文本
- for i, paragraph in enumerate(doc.paragraphs):
- if paragraph.text.strip():
- all_text.append(paragraph.text)
- logger.info(f"段落 {i}: {paragraph.text}")
-
- # 检查表格中的文本
- for t_idx, table in enumerate(doc.tables):
- for r_idx, row in enumerate(table.rows):
- for c_idx, cell in enumerate(row.cells):
- for p_idx, paragraph in enumerate(cell.paragraphs):
- if paragraph.text.strip():
- all_text.append(paragraph.text)
- logger.info(f"表格 {t_idx}, 行 {r_idx}, 列 {c_idx}, 段落 {p_idx}: {paragraph.text}")
-
- # 查找所有变量
- variables = set()
- for text in all_text:
- # 查找形如 {xxx} 的模式
- start = 0
- while True:
- start = text.find('{', start)
- if start == -1:
- break
- end = text.find('}', start)
- if end == -1:
- break
- potential_var = text[start:end+1]
- variables.add(potential_var)
- start = end + 1
-
- logger.info(f"在模板中找到以下变量: {variables}")
- return variables
- if __name__ == "__main__":
- template_folder = 'template'
- template_files = [f for f in os.listdir(template_folder)
- if f.lower().endswith('.docx') and not f.startswith('~$')]
-
- if not template_files:
- logger.error("模板文件夹中没有找到有效的.docx文件")
- else:
- # 使用第一个模板文件
- template_filename = template_files[0]
- template_path = os.path.join(template_folder, template_filename)
- variables = check_template_variables(template_path)
-
- print("\n在模板中找到以下变量:")
- for var in sorted(variables):
- print(f"- {var}")
|