首页 > 解决方案 > 正则表达式:如何将 LaTeX 分数转换为 Python 中的可操作表达式?

问题描述

我想创建一个解析器,它接受任何 LaTeX 格式的字符串并返回 Python 可以评估的表达式。

我有几个分数问题。下面是一些例子:

乳胶(输入) 可互操作的字符串(输出)
\frac{1}{2} ((1)/(2))
\frac{x}{3b} ((x)/(3b))
\frac{2-m}{3} ((2-m)/(3))
\frac{7}{5+y} ((7)/(5+y))

这是我到目前为止所尝试的:

fraction_re = re.compile(r"\\frac{(.*?)}{(.*?)}")

def parser(expression):

    fractions = fraction_re.findall(expression)

    for numerator, denominator in fractions:
        pattern = r"\\frac\{%s\}\{%s\}" % (numerator, denominator)
        replace = f"(({numerator})/({denominator}))"
        expression = re.sub(pattern=pattern, repl=replace, string=expression)

    return expression

这适用于案例一和案例二(见表格),但案例三和案例四有问题。我怀疑-+符号会引起问题,因为它们本身就是正则表达式元字符。

我想添加一些额外的行来逃避它们,例如

numerator = re.sub(pattern='+', repl='\+', string=numerator)

但这并没有让我觉得这是一个好的长期策略。我也尝试在pattern变量中添加方括号(因为方括号中的普通正则表达式符号不会被解释为这样),即

pattern = r"\\frac\{[%s]\}\{[%s]\}" % (numerator, denominator)

但这也不起作用。

谁能帮我?

提前致谢。

ps

我知道这已经被问过很多次了(例如Python Regex to Simplify LaTex Fractions Using Python Regex to Simplify Latex Fractions Using if-then-else conditionals with Python regex replacement)但我觉得他们的问题与我的,我还没有找到对我有很大帮助的答案。

此外,我知道已经存在开箱即用的解析器,它们可以完全满足我的需求(例如:https ://github.com/august198/latex2sympy ),但我真的很想自己构建它。

标签: pythonregexlatex

解决方案


您可以使用一个简单的 lambda 函数,re.sub()如下所示:

import re

data = r"""
some very cool \textbf{Latex} stuff

\begin{enumerate}
\item even a very cool item
\end{enumerate}

Here comes the fun
\frac{1}{2} 
\frac{x}{3b}
\frac{2-m}{3}
\frac{7}{5+y}
"""

rx = re.compile(r'\\frac\{(?P<numerator>[^{}]+)\}\{(?P<denominator>[^{}]+)\}')

data = rx.sub(lambda m: f"(({m.group('numerator')}/({m.group('denominator')})", data)
print(data)

哪个会产生

some very cool \textbf{Latex} stuff

\begin{enumerate}
\item even a very cool item
\end{enumerate}

Here comes the fun
((1/(2)
((x/(3b)
((2-m/(3)
((7/(5+y)

表达式归结为

\\frac\{(?P<numerator>[^{}]+)\}\{(?P<denominator>[^{}]+)\}

不需要使用命名组,真的,只是为了让它一目了然。


推荐阅读