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()

 

posted @ 2019-03-21 15:58  wind_y  阅读(2860)  评论(0编辑  收藏  举报