Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

Using Python Regex to Simplify Latex Fractions

Sample code in Latex:

%Chebyshev of second kind
egin{equation}
sum_{ell hiderel{=} 0}^nfrac{( ChebyU{ell}@{x}  )^2}*{ frac{pi}{2}  }*=frac{ 2^n  }{ frac{pi}{2}   2^n+1  }frac{ ChebyU{n+1}@{x}   ChebyU{n}@{y}  - ChebyU{n}@{x}   ChebyU{n+1}@{y}  }{x-y}
end{equation}

frac{(ChebyU{ell}@{x})^2}*{frac{pi}{2}} is the fraction I am looking at for this specific case. Since it is a fraction in the denominator of another fraction I would like to use Python regex to change this from a/(b/c) to (ac)/b.

Example output:

%Chebyshev of second kind
egin{equation}
sum_{ell hiderel{=} 0}^nfrac{(2 ChebyU{ell}@{x}  )^2}{pi}*=frac{ 2^n  }{ frac{pi}{2}   2^n+1  }frac{ ChebyU{n+1}@{x}   ChebyU{n}@{y}  - ChebyU{n}@{x}   ChebyU{n+1}@{y}  }{x-y}
end{equation}

End result: frac{(2ChebyU{ell}@{x})^2}{pi} is the fraction that the regex should result in.

How would I go about doing this with regex in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a regex that should work. Note that I made a change in your LaTeX expression because I think there was an error (* sign).

astr = 'frac{(ChebyU{ell}@{x})^2}{frac{pi}{2}}'

import re
pat = re.compile('\frac{(.*?)}{\frac{(.*?)}{(.*?)}}')
match = pat.match(astr)
if match:
    expr = '\frac{{{0}*{2}}}{{{1}}}'.format(*match.groups())
    print expr

NB: I did not include the spaces in your original expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...