python - 如何在 django 模板中转义 LaTeX 特殊字符?

标签 python django pdflatex

我有这个用于生成 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/

相关文章:

django - 如何使用 Django 模板存储 templatetag 的结果?

python - 使用 scapy 时 PyX 安装不正确

pdf - 在 latex #2 中插入 pdf 文件

python - 如何在使用 for 循环时仅打印 'date received' 一次?

python - numpy 排列的 2D

python - 从列表列表中的项目形成数组

python - 本地托管 Django 项目

python - 根据条件更改列的值

python - 内存泄漏 - gunicorn + django + mysqldb

针织 Rnw latex : how to obtain a figure and caption in landscape mode that's full page width