python - 正则表达式:如何将 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 ),但我真的很想自己构建它。
解决方案
您可以使用一个简单的 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>[^{}]+)\}
不需要使用命名组,真的,只是为了让它一目了然。
推荐阅读
- fpm - php-fpm 处理大量请求/用户的正确配置应该是什么?
- python - 前导零的数字字符串列表中的 Python sorted() 未按预期运行
- reactjs - 更新反应状态中的字典列表
- swift - 无法创建 Firebase 集合
- powershell - 如果写入文件,Get-PnpDevice 不起作用
- blazor - 未处理的异常呈现组件:“<”是 Blazor WASM 值的无效开始
- javascript - YT 播放器在悬停时删除个人资料图片和 youtube 徽标
- python - 将 PySimpleGUI 窗口变量导入另一个文件
- microsoft-graph-api - 当我的机器人安装到新团队时,我不会收到 conversationUpdate (membersAdded) 事件有什么原因吗?
- tcp - Wireshark - TCP SYN、SYN ACK 和来自服务器的确认号