用正则表达式实现简单计算器

#1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
import re
def check_text(str): #处理连续运算符
str = str.replace("++","+")
str = str.replace("-+","-")
str = str.replace("+-","-")
str = str.replace("--","+")
return str

def mul_div(text): #处理乘除法
while re.findall(r'[*/]',text):
textNew = re.search(r'\d+\.?\d*[*/](-)?\d+\.?\d*',text).group(0)
if re.findall(r'\*',textNew):
textList = textNew.split('*')
result = float(textList[0]) * float(textList[1])
text = text.replace(textNew,str(result))
else:
textList = textNew.split('/')
result = float(textList[0]) / float(textList[1])
text = text.replace(textNew,str(result))
return text

def add_sub(text): #处理加减法
while re.findall(r'(-)?\d+\.?\d*[+-](-)?\d+\.?\d*',text):
textNew = re.search(r'(-)?\d+\.?\d*[+-](-)?\d+\.?\d*',text).group(0)
if re.findall(r'\+',textNew):
textList = textNew.split('+')
result = float(textList[0]) + float(textList[1])
text = text.replace(textNew,str(result))
else:
textList = textNew.split('-')
result = float(textList[0]) - float(textList[1])
text = text.replace(textNew,str(result))
return text

def deal_paren(str): #处理最里面的括号
while True:
if re.search(r'\(([^()])+\)',str):
lessParen = re.search(r'\(([^()])+\)',str)
if lessParen:
lessParen = lessParen.group(0)
if re.findall(r'[*/]',lessParen):
str1 = mul_div(lessParen)
str1 = str1[1:-1]
if re.findall(r'(\(-)?\d+\.?\d*[+-]\d+\.?\d*',str1):
str2 = add_sub(str1)
str = re.sub(r'\(([^()])+\)', str2, str,1)
else:
str = re.sub(r'\(([^()])+\)', str1, str,1)
str = check_text(str)
else:
strNmd = mul_div(str)
strNmd = check_text(strNmd)
strNas = add_sub(strNmd)
print(strNas)
break
return str

def main(): #函数入口
str = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
str = str.replace(" ","")
str_no_paren = deal_paren(str)


main()

posted @ 2018-08-04 11:02  我是王亮啊hhh  阅读(470)  评论(0编辑  收藏  举报