15

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 ファイルの生成中にエラーが発生します。

すべての列のすべてのテキストをエスケープするにはどうすればよいですか?

4

2 に答える 2

27

コピーして貼り付けたい場合は、コード内の提案を含むアレックスの回答:

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)

置換の辞書を使用して文字列を置き換える最も簡単な方法を参照してください。交換アプローチ用。

于 2014-09-16T17:57:10.923 に答える