如何自动将值插入到乳胶代码/模板中

如何自动将值插入到乳胶代码/模板中

我正在用 latex 生成 pdf 格式的自动报告。每份报告都一样,但值/图表不同。图表没有问题,但处理 latex 模板并在预定义位置插入值的最佳方法是什么?

对于如何做到这一点,您有什么想法吗?

谢谢!

答案1

笔记:这个问题最初是在 stackoverflow.com 上提出的,带有python标签,因此是 python 角度

你应该使用str.format 方法方法。例如

>>> msg = r"""\section{{{section}}}
... 
... An unladen swallow needs to beat its wings {frequency} times every second,
... right?""".format(section="Aviation", frequency=43)
>>> print msg
\section{Aviation}

An unladen swallow needs to beat its wings 43 times every second,
right?

文字花括号需要加倍,我r在三重引号前面使用 (原始字符串) 以避免在下一个字母恰好是 或 时必须n转义r反斜杠t


回复:评论

我想我会定义一个带有两个参数的新 LaTeX 命令。该命令的输出只是第二个参数的内容:

\newcommand{\mergefield}[2]{#2}

然后,当该文件用作模板时,我会使用第一个参数作为字段名称。

现在,如果您想在生成报告时更改部分标题,请使用以下代码:

\section{Normal section heading}

使用此代码:

\section{\mergefield{section_3}{Normal section heading}}

读取文件后我们需要做两处替换才能将其作为 Pythonstr.format模板字符串:

  1. 将所有{}字符加倍,这样它们就不会被解释为字段str.format
  2. \mergefield{{abc}}{{xyz}}用字段替换所有命令{abc}

例子:

# This would be read from file normally...
template = r"\section{\mergefield{section_3}{Default section heading}}"

# Double curly braces
template = template.replace("{", "{{").replace("}", "}}")

# Replace template field markers with `str.format` fields.
template = re.sub(
    r"\\mergefield\{\{([^}]+)\}\}\{\{[^}]*\}\}", "{\\1}", template)

现在template等于'\section{{{section}}}',我们可以按照我最初的建议来格式化模板。

>>> template.format(section_3="My custom section title")
'\section{My custom section title}'

您的字段名称可以包含任何字符,但不能包含花括号。

答案2

这听起来很像格式化字符串。它是否是 Latex 文档并不重要。您可以阅读如何格式化字符串(包括在预定义位置插入值)>这里<

编辑:将链接更改为新的改进的字符串格式化 API。(感谢 Lauritz V. Thaulow)

相关内容