- 移除原有的 docx_thesis 模块及其相关文件 (cli.py, config.py, converter.py) - 新增 .claudeignore 文件以忽略 Python 生成文件和缓存 - 更新 .gitignore 文件添加更多忽略规则包括 .mypy_cache/, .ruff_cache/, .claude/, *.md 等 - 添加 README.md 使用说明文档 - 修改 pyproject.toml 依赖配置,新增 docxtpl、pyyaml, 移除原 thesis 命令入口点并更新为 transit.__main__ - 新增 transit 模块及相应初始化文件 - 重命名 main.py 为快速入口脚本
88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
"""
|
|
Markdown 正文 → Word 段落转换。
|
|
|
|
将正文 Markdown 按标题层级拆分为带样式的段落序列,
|
|
再注入到渲染后 docx 文档的占位符位置。
|
|
"""
|
|
|
|
import re
|
|
from docx import Document
|
|
|
|
_PAT_HEADING = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
|
|
|
|
|
|
def body_to_paragraphs(md_text: str) -> list[dict]:
|
|
"""将 Markdown 正文按标题和段落拆分为结构化列表。
|
|
|
|
返回的每个元素::
|
|
{"text": str, "level": int, "style": str}
|
|
其中 ``style`` 为 ``Heading N`` 或 ``Normal``。
|
|
"""
|
|
paragraphs: list[dict] = []
|
|
last_end = 0
|
|
|
|
for m in _PAT_HEADING.finditer(md_text):
|
|
# 标题前的普通文本
|
|
if m.start() > last_end:
|
|
pre = md_text[last_end : m.start()].strip()
|
|
if pre:
|
|
for block in re.split(r"\n\s*\n", pre):
|
|
block = block.strip()
|
|
if block:
|
|
paragraphs.append(
|
|
{"text": block, "level": 0, "style": "Normal"}
|
|
)
|
|
|
|
level = len(m.group(1))
|
|
heading_text = m.group(2).strip()
|
|
paragraphs.append(
|
|
{"text": heading_text, "level": level, "style": f"Heading {level}"}
|
|
)
|
|
last_end = m.end()
|
|
|
|
# 最后一段 / 尾部文本
|
|
tail = md_text[last_end:].strip()
|
|
if tail:
|
|
for block in re.split(r"\n\s*\n", tail):
|
|
block = block.strip()
|
|
if block:
|
|
paragraphs.append(
|
|
{"text": block, "level": 0, "style": "Normal"}
|
|
)
|
|
|
|
return paragraphs
|
|
|
|
|
|
def replace_placeholder(doc: Document, placeholder: str, paragraphs: list[dict]):
|
|
"""在 *doc* 中找到包含 *placeholder* 的段落,替换为 *paragraphs* 列表。
|
|
|
|
每个段落的 ``style`` 字段会从文档样式中查找并应用。
|
|
"""
|
|
placeholder_found = False
|
|
for para in doc.paragraphs:
|
|
if placeholder in para.text:
|
|
placeholder_found = True
|
|
parent = para._element.getparent()
|
|
idx = list(parent).index(para._element)
|
|
parent.remove(para._element)
|
|
|
|
for pd_data in reversed(paragraphs):
|
|
new_p = doc.add_paragraph(pd_data["text"])
|
|
style_name = pd_data["style"]
|
|
try:
|
|
new_p.style = doc.styles[style_name]
|
|
except KeyError:
|
|
matched = False
|
|
for s in doc.styles:
|
|
if s.name.lower() == style_name.lower():
|
|
new_p.style = s
|
|
matched = True
|
|
break
|
|
if not matched:
|
|
new_p.style = doc.styles["Normal"]
|
|
parent.insert(idx, new_p._element)
|
|
break
|
|
|
|
if not placeholder_found:
|
|
print(f"警告:未找到占位符 '{placeholder}',正文段落未注入。")
|