Ga *_*eeu 3 python latex jinja2
我是一个新手,正在探索模板引擎 Jinja2 来帮助我使用 Python 排版几个 LaTeX 文档。在我最初的探索中,我只是尝试在 Python 中使用以下代码填充表:
latex_jinja_env = jinja2.Environment(
block_start_string = '\BLOCK{',
block_end_string = '}',
variable_start_string = '\VAR{',
variable_end_string = '}',
comment_start_string = '\#{',
comment_end_string = '}',
line_statement_prefix = '%%',
line_comment_prefix = '%#',
trim_blocks = True,
autoescape = False,
loader = jinja2.FileSystemLoader(os.path.abspath('.'))
)
header = ['Num', 'Date', 'Ticker']
data = [[1, 2, 3], [4, 'STR', 'Test'], [5, 6, 'Ticker']]
template = latex_jinja_env.get_template('template.tex')
print(template.render(section1='Test Table', header = header, data = data))
Run Code Online (Sandbox Code Playgroud)
LaTeX 模板的构造如下:
\documentclass[12pt,a4paper]{article}
\begin{document}
\section{\VAR{section1}}
\BLOCK{set colsep = joiner("&")}
\begin{tabular}{ ccc }
\hline
\BLOCK{for col in header} \VAR{colsep()} \textbf{\VAR{col}} \BLOCK{endfor} \\
\hline
\hline
\BLOCK{for row in data} \BLOCK{for col in row} \VAR{colsep()} \VAR{col} \BLOCK{endfor} \\
\BLOCK{endfor}
\hline
\end{tabular}
\end{document}
Run Code Online (Sandbox Code Playgroud)
虽然标题是根据需要生成的,但关于数据,似乎在数据前面添加了一个空列:
bash-3.2$ ./rep.py
\documentclass[12pt,a4paper]{article}
\begin{document}
\section{Test Table}
\begin{tabular}{ ccc }
\hline
\textbf{Num} & \textbf{Date} & \textbf{Ticker} \\
\hline
\hline
& 1 & 2 & 3 \\
& 4 & STR & Test \\
& 5 & 6 & Ticker \\
\hline
\end{tabular}
\end{document}
bash-3.2$
Run Code Online (Sandbox Code Playgroud)
用数据填充模板表的正确方式是什么?预先感谢您帮助这个新手。
小智 5
我不知道你是否找到答案,但尝试这样:
data2 = [[1, 2, 3], [4, 'STR', 'Test'], [5, 6, 'Ticker']]
renderer_template = template.render(dict_map = data2, header = header)
Run Code Online (Sandbox Code Playgroud)
您应该像字典一样粘贴数据,因此您可以单独粘贴数据的每个元素。
然后在你的 template.tex 文件中你将有这样的内容:
\begin{document}
\begin{tabular}{ ccc }
\BLOCK{for col in header}
\BLOCK{if loop.last} %checks if loop reached to the end
\VAR{col}
\BLOCK{else}
\VAR{col} &
\BLOCK{endif}
\BLOCK{endfor} \\
\BLOCK{for col in dict_map}
\VAR{col[0]} & \VAR{col[1]} & \VAR{col[2]} \\
\BLOCK{endfor} \\
\end{tabular}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,标题仅在一列中打印,如果您希望标题中的每个项目都在单独的列中,则必须将标题项目作为 item1 和 item2 获取,但最后一项没有符号“&”,因此您必须检查循环何时到达最后一项“loop.last”。对于数据也是如此,您必须获取数据中项目的每个子项目,例如 col[0] 获取 1 等等。
ps 我不是 Latex 和 jinja2 方面的专家
| 归档时间: |
|
| 查看次数: |
5690 次 |
| 最近记录: |