本文介绍了如何在Django模板中转义LaTeX特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个django模板,可用来生成LaTeX文件
I have this django template which I use to generate LaTeX files
\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}
但是我的列数非常大,因此它们可以包含任何特殊字符。
But my no of columns are very large so they can contain any special characters in them. I am getting error while generating pdf file.
如何转义所有列中的所有文本?
How can I escape all the text in all columns?
推荐答案
如果要复制粘贴,Alex的答案包括代码建议:
Alex's answer including suggestions in code, if you want to copy-paste:
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)
请参见替换方法。
这篇关于如何在Django模板中转义LaTeX特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!