使用LaTeX-OCR提取公式后,latex2sympy转换报错求助
问题:LaTeX转SymPy处理公式报错
问题背景
用latex-ocr从图片提取数学公式后,尝试用latex2sympy在Python中处理该公式,出现解析错误。
运行代码
from PIL import Image from pix2tex.cli import LatexOCR from latex2sympy2 import latex2sympy, latex2latex i = Image.open(myfile) model = LatexOCR() print(model(i)) # 输出结果为 \sum_{j}^{G}\sum_{l=1}^{M_{j,s p,i}}f_{j}\bigl(X,Y_{\dots}\bigr)^{\star\kappa}\,C F_{j} t = r"\sum_{j}^{G}\sum_{l=1}^{M_{j,s p,i}}f_{j}\bigl(X,Y_{\dots}\bigr)^{\star\kappa}\,C F_{j}" s = latex2sympy(t) print(s)
报错信息
NoViableAltException: None During handling of the above exception, another exception occurred: LexerNoViableAltException Traceback (most recent call last) LexerNoViableAltException: LexerNoViableAltException('\\') During handling of the above exception, another exception occurred: Exception Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/latex2sympy2.py in syntaxError(self, recog, symbol, line, col, msg, e) 139 else: 140 err = fmt % ("I don't understand this", self.src, marker) --> 141 raise Exception(err) 142 143 Exception: I don't understand this \sum_{j}^{G}\sum_{l=1}^{M_{j,s p,i}}f_{j}\bigl(X,Y_{\dots}\bigr)^{\star\kappa} C F_{j}
解决方案
latex2sympy对LaTeX语法的支持有限,需要调整提取后的LaTeX表达式,适配其解析规则:
- 替换扩展括号:
\bigl(→(,\bigr)→),latex2sympy不识别这类排版用的括号 - 替换省略号:
\dots→\cdots,SymPy更兼容标准数学省略号 - 替换特殊符号:
\star→*,latex2sympy无法解析\star作为乘法符号 - 合并变量空格:
C F→CF,空格会被解析为变量分隔,导致识别为两个独立变量 - 修正下标空格:
M_{j,s p,i}→M_{j,sp,i},下标内的空格会引发解析错误
修改后的代码示例:
from latex2sympy2 import latex2sympy # 适配latex2sympy的LaTeX字符串 t = r"\sum_{j}^{G}\sum_{l=1}^{M_{j,sp,i}}f_{j}(X,Y_{\cdots})^{* \kappa} CF_{j}" s = latex2sympy(t) print(s) # 输出可用于Python处理的SymPy表达式
内容的提问来源于stack exchange,提问作者User202010
相关产品推荐
相关产品推荐

