我有这个用于生成 LaTeX 文件的 django 模板
\documentclass[11pt]{report}
\begin{document}
\begin{table}
\centering
\begin{tabular}{lcr}
\hline
{% for col in head %}
\textbf{ {{col}} }
{% if not forloop.last %}
&
{% endif %}
{% endfor %}
\\
\hline
{% for row in table %}
{% for cell in row %}
{% if not forloop.last %}
&
{% endif %}
{% endfor %}
\\
{% endfor %}
\hline
\end{tabular}
\caption{Simple Phonebook}
\label{tab:phonebook}
\end{table}
\end{document}
但是我的列数非常大,所以它们可以包含任何特殊字符。生成 pdf 文件时出现错误。
如何转义所有列中的所有文本?
最佳答案
Alex 的回答包括代码中的建议,如果你想复制粘贴:
import re
def tex_escape(text):
"""
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX
"""
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless{}',
'>': r'\textgreater{}',
}
regex = re.compile('|'.join(re.escape(str(key)) for key in sorted(conv.keys(), key = lambda item: - len(item))))
return regex.sub(lambda match: conv[match.group()], text)
参见 Easiest way to replace a string using a dictionary of replacements?用于替换方法。
关于python - 如何在 django 模板中转义 LaTeX 特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259923/