我正在編寫一個(gè)解析器,而不是將LaTeX數(shù)學(xué)轉(zhuǎn)換為與 pythoneval()兼容的字符串。我得到了一個(gè)看起來像這樣的字符串:\sqrt{4m/s} - \frac{3v+10.5v}{20a-8a} +1/2請注意仍然主要的LaTeX語法,以及一些任意的“單位”字母。然后我使用以下否定集來替換除否定集中的內(nèi)容之外的所有內(nèi)容。 mathstr = re.sub('[^0-9*()/+\-.Q]','',mathstr)我如何包含一個(gè)子字符串“sqrt”,以便它可以以類似的方式工作,最好是在相同的正則表達(dá)式中?現(xiàn)在我的工作是用 ' \sqrt'替換 ' ' Q,執(zhí)行上面的代碼行,然后將 ' Q'設(shè)置為 ' sqrt',我從上述語法到eval()語法的完整例程如下: mathstr = mathstr.replace(" ","") if pwrRe.search(mathstr): mathstr = re.sub(pwrRe,'**',mathstr) if MultiplyRe.search(mathstr): mathstr = re.sub(MultiplyRe,'*',mathstr) if DivideRe.search(mathstr) or sqrtRe.search(mathstr): mathstr = re.sub('\\\\frac{','(',mathstr) mathstr = re.sub('\\\\sqrt{','\\\\sqrt(',mathstr) mathstr = re.sub('}{',')/(',mathstr) mathstr = re.sub('}',')',mathstr) mathstr = re.sub('[/*+\-^][a-zA-Z]','',mathstr) mathstr = re.sub('\\\\sqrt','Q',mathstr) mathstr = re.sub('[^0-9*()/+\-.Q]','',mathstr) mathstr = re.sub(r'Q','sqrt',mathstr)這導(dǎo)致eval()語法'd:sqrt(4)-(3+10.5)/(20-8)+1/2但這是草率的,如果我可以在一行中“白名單”字符和子字符串,將所有其他出現(xiàn)的字符吹走,那么它在許多領(lǐng)域都會很有用。
添加回答
舉報(bào)
0/150
提交
取消