Python Regex To Simplify Latex Fractions
This is my python program: def fractionSimplifier(content): content.replace('\\dfrac','\\frac') pat = re.compile('\\frac\{(.*?)\}\{\\frac\{(.*?)\}\{(.*?)\}\}') match =
Solution 1:
A few issues here.
pat.matchchecks only at the beginning of the string. You wantpat.searchthere.In
re.compilecommand you escape{}which is unnecessary, and do not escape backslashes enough. As written,\\finside string quotes is understood as\f, which then is understood as a control character by re library. Either put four backslashes\\\\for, better, use raw string input (explained here):
re.compile(r'\\frac{(.*?)}{\\frac{(.*?)}{(.*?)}}')
.format(*match.group())should be.format(*match.groups())
With the above changes, it works somewhat: the output for your "Chebyshev of second kind" example is
\frac{(\ChebyU{\ell}@{x})^2*2}{\pi}
as intended.
Additional remarks:
- Your code doesn't deal with multiple matches at present
- You have no code for substituting expr back into the original string in place of the match
- Instead of asterisk, in LaTeX one uses
\cdot - Parsing complex math formulas with regex is generally a bad idea.
Post a Comment for "Python Regex To Simplify Latex Fractions"