【问题标题】:How to format a LaTeX string in python?如何在 python 中格式化 LaTeX 字符串?
【发布时间】:2011-10-04 01:44:54
【问题描述】:

我正在编写一个应用程序,其部分功能是生成 LaTeX CV,所以我发现自己遇到了这样的情况

\begin{document}
\title{Papers by AUTHOR}
\author{}
\date{}
\maketitle
\begin{enumerate}

%%   LIST OF PAPERS
%%   Please comment out anything between here and the
%%   first \item
%%   Please send any updates or corrections to the list to
%%   XXXEMAIL???XXX

%\usepackage[pdftex, ...

我想用动态信息填充,例如一个电子邮件地址。由于 LaTeX 本身的格式,带有 {email} 语法的 .format 将不起作用,也不会使用带有 %(email)s 语法的字典。编辑:特别是,像“\begin{document}”(LaTeX 中的命令)这样的字符串应该保持原样,而不是从 .format 替换,并且像“%%”(LaTeX 中的注释)这样的字符串也应该是左,没有从填充字典中替换。这样做的合理方法是什么?

【问题讨论】:

  • 假设我真的不想在任何地方都为 % 键入 %% ...
  • 您使用的是什么版本的 Python? str.format() 是 2.6 的新功能
  • 你有没有完成过这个库,因为我刚刚创建了类似的东西:github.com/JelteF/PyLaTeX
  • 酷!我确实完成了这个项目的工作,您可以在invenio-software.org 找到它的源代码(仍然是由其他人开发的,而不是由我开发的)。我没有把 LaTeX 分成任何好东西,所以有人做了一件好事。 :)

标签: python string latex format


【解决方案1】:

为什么这不起作用?

>>> output = r'\author{{email}}'.format(email='user@example.org')
>>> print output
\author{email}

编辑:使用双花括号“转义”只有 LaTeX 理解的文字花括号:

>>> output = r'\begin{{document}} ... \author{{{email}}}'.format(
... email='user@example.org')
>>> print output
\begin{document} ... \author{user@example.org}

【讨论】:

  • out = r''' ...: \begin{document} ...: {{email}}'''.format(email='user@example.com') -- -------------------------------------------------- ------------------------------------ KeyError Traceback(最近一次调用最后)/home/valkyrie/projects/invenio/modules/websearch/lib/() KeyError: 'document'
  • LaTeX 包含带有花括号的东西,应该保持不变(包括花括号本身)。
  • 所以对那些使用双花括号(基本上是转义它们。
  • 遗憾的是,唯一的出局是卷曲或百分比加倍,但只要它有效,我想这一切都很好。 :)
【解决方案2】:

您不能使用新的format 语法来避免转义{}

应该可以的:

>>> a = r'''
\title{%(title)s}
\author{%(author)s}
\begin{document}'''

>>> b = a % {'title': 'My Title', 'author': 'Me, Of course'}
>>> print(b)

\title{My Title}
\author{Me, Of course}
\begin{document}

您应该使用原始字符串 r'something' 以避免将 \ 转义为 \\

PS:你应该看看txt2tags,这是一个将 t2t 格式文本转换为 html、latex、markdown 等的 Python 脚本。查看源代码以了解这些转换是如何完成的。

【讨论】:

  • 它抱怨 LaTeX 的 cmets,例如我有一行写着“%\usepackage....”,这会导致字典格式化程序抱怨。不过,我会研究一下 txt2tags,谢谢!
  • 您可以在格式化后添加 cmets... 或者使用 \% 转义 %
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
相关资源
最近更新 更多