簡體   English   中英

如何在 python 中格式化 LaTeX 字符串?

[英]How to format a LaTeX string in python?

我正在編寫一個應用程序,其部分功能是生成 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, ...

我想填充動態信息,例如 email 地址。 由於 LaTeX 本身的格式,帶有 {email} 語法的 .format 將不起作用,也不會使用帶有 %(email)s 語法的字典。 編輯:特別是,像“\begin{document}”(LaTeX 中的命令)這樣的字符串應該保持原樣,而不需要替換 from.format,並且像“%%”(LaTeX 中的注釋)這樣的字符串也應該是左,沒有從填充字典中替換。 這樣做的合理方法是什么?

為什么這行不通?

>>> 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}

您不能使用新的format語法來避免 escaping {}

那應該工作:

>>> 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'來避免 escaping \ as \\

PS: You should take a look on txt2tags , a Python script to convert t2t formatted text into html, latex, markdown etc. Check the source code to see how these conversions are done.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM