python用re模塊實現數學公式計算


不完善:1.如果公式里沒()

    2.算到中間部,可能有*-, +- ,-- ,這樣的情況

import re

'''計算字符串表達式'''
bracket = re.compile('\([^()]+\)')  # 查找最內層括號
div = re.compile('(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)')  # 查找除法運算
mul = re.compile('(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)')  # 查找乘法運算
add = re.compile('(-\d+\.?\d*\+\d+\.?\d*)|(\d+\.?\d*\+\d+\.?\d*)')  # 查找加法運算
sub = re.compile('(-\d+\.?\d*-\d+\.?\d*)|(\d+\.?\d*-\d+\.?\d*)')  # 查找減法運算
c_f=re.compile('\(?\d+\)?')
strip=re.compile('[^()]')

def Div(s):
    exp = re.split('/', div.search(s).group())
    return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1])))


def Mul(s):
    exp = re.split('\*', mul.search(s).group())
    return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1])))


def Add(s):
    exp = re.split('\+', add.search(s).group())
    return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1])))


def Sub(s):
    exp = sub.search(s).group()
    if exp.startswith('-'):
        exp = exp.replace('-', '+')
        exp = exp.replace('+', '', 1)
        res = Add(exp)
        return s.replace(sub.search(s).group(), '-' + res)

    else:
        exp = re.split('-', sub.search(s).group())
        return s.replace(sub.search(s).group(), str(float(exp[0]) - float(exp[1])))


def calc():
    while True:
        s = input('請輸入等式').replace(' ','')
        if s=='quit':
            break
        else:
            while bracket.search(s):
                s_search=bracket.search(s).group()
                if div.search(s_search):
                    s=s.replace(s_search,Div(s_search))
                elif mul.search(s_search):
                    s=s.replace(s_search,Mul(s_search))
                elif sub.search(s_search):
                    s = s.replace(s_search, Sub(s_search))
                elif add.search(s_search):
                    s=s.replace(s_search,Add(s_search))
                elif c_f.search(s_search):
                    s=s.replace(s_search,strip.search(s_search).group())
            print(s)

calc()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM