from re import sub as replace
from re import search as find
from re import split
'''***********解析四则算式并计算***********'''
'''全局正则定义'''
#乘除正则,查找乘除操作
mul_div_calc_regex = r'\d+(\.\d+)?[\*\/]\d+(\.\d+)?'
#加减正则,查找加减操作
plus_sub_calc_regex = r'\d+(\.\d+)?[\+\-]\d+(\.\d+)?'
#括号正则,查找括号运算
mark_regex = r'\([^\(]*?\)'
#运算正则,查找具体操作
calc_regex = r'[\+\-\*\/]'
def basic_calc(a,mark, b):
'''简单计算'''
a = float(a)
b = float(b)
ans = 0
if mark == '*':
ans = a*b
elif mark == '/':
ans = a/b
elif mark == '+':
ans = a+b
elif mark == '-':
ans = a-b
return ans
def calc_by_string(s):
'''字符串拆分计算'''
global calc_regex
a = split(calc_regex,s)
mark = find(calc_regex,s).group()
return basic_calc(a[0],mark, a[1])
def mul_div(s):
'''查找字符串中加减操作,并计算'''
global mul_div_calc_regex
while find(mul_div_calc_regex, s):
a = find(mul_div_calc_regex, s).group()
ans = calc_by_string(a)
s = replace(mul_div_calc_regex, str(ans), s,count=1)
return s
def plus_sub(s):
'''查找字符串中乘除操作,并计算'''
global plus_sub_calc_regex
while find(plus_sub_calc_regex, s):
a = find(plus_sub_calc_regex, s).group()
ans = calc_by_string(a)
s = replace(plus_sub_calc_regex, str(ans), s,count=1)
return s
def calc_one(s):
'''计算一个简单等式,不包含括号'''
return plus_sub(mul_div(s))
def mark_calc(s):
'''查找括号,并计算'''
global mark_regex
while find(mark_regex,s):
print(s)
a = find(mark_regex, s).group()
ans = calc_one(replace(r'[\(\)]','',a))
s = replace(mark_regex,ans,s,count=1)
print(s)
return s
def calc_all(s):
'''全部计算'''
return plus_sub(mul_div(mark_calc(s)))
test_string = '1+(9+(32*1)+(25/5)-3)*(3*9-5+3)'
print(calc_all(test_string))
计算过程显示如下
1+(9+(32*1)+(25/5)-3)*(3*9-5+3)
1+(9+32.0+(25/5)-3)*(3*9-5+3)
1+(9+32.0+5.0-3)*(3*9-5+3)
1+43.0*(3*9-5+3)
1+43.0*25.0
1076.0