最近几周迷上了Python,看了几天的Python后,尝试着写了一个计算器,经过几个小时的硬怼 总算是用正则表达式实现了计算器符合运算的功能。只要会了正则表达式,那就没啥难的了,主要还是正则的运用。只实现了计算,没写判断输入的是否合法,以后有心情的话再加吧。
code:
# @Time : 2018/6/10 17:34
# @Author : 非人类浩
import re
def format_out(s):#格式化输出
s = str.replace(s,' ','')
s = str.replace(s,'++','+')
s = str.replace(s,'--','+')
s = str.replace(s,'+-','-')
s = str.replace(s,'-+','-')
return s
def multiply_divide(s):#处理2*3类的乘除问题,返回字符串
num = re.findall(r'-*\d+\.*\d*',s)
flag = re.findall('[*/]',s)
if flag[0] == '*':
return str(float(num[0])*float(num[1]))
elif flag[0] == '/':
return str(float(num[0])/float(num[1]))
def mul_div(s):#处理一个没有括号的算式里的所有乘除问题
while re.search(r'\d+\.*\d*[*/]-*\d+\.*\d*',s)!=None:
tmp = re.search(r'\d+\.*\d*[*/]-*\d+\.*\d*', s).group()
# print(tmp)
ans = multiply_divide(tmp)
# print(ans)
s = s.replace(tmp,ans)
# print(s)
return s
#处理2+3类的加减问题
def add_subtract(s):
num = re.findall(r'\d+\.*\d*',s)
flag = re.findall('[+-]',s)
if re.match('-',s)!=None:
num[0] = str(-float(num[0]))
del flag[0]
if flag[0] == '+':
return str(float(num[0])+float(num[1]))
elif flag[0] == '-':
return str(float(num[0])-float(num[1]))
#处理一个没有括号的算式里的所有加减问题
def add_sub(s):
while re.search(r'[+-]*\d+\.*\d*[+-]\d+\.*\d*',s)!=None:
tmp = re.search(r'[+-]*\d+\.*\d*[+-]\d+\.*\d*',s).group()
# print(tmp)
ans = add_subtract(tmp)
# print(ans)
s = s.replace(tmp,ans)
# print(s)
return s
#处理不包含括号的算式
def first_ans(s):
tmp = mul_div(s)
ans = add_sub(tmp)
return ans
#处理括号问题
def bracket(s):
while re.search(r'\([^()]*\)',s)!=None:#有括号
tmp = re.search(r'\([^()]*\)',s).group()#tmp保存最里面的括号以及内容
# print(tmp,type(tmp))
t = re.findall(r'[^()]*',tmp)[1]
# print(t)
ans = first_ans(t)
# print(ans)
s = s.replace(tmp,ans)
s = format_out(s)
s = first_ans(s)
return s
while True:
num = input("输入想要计算的算式(输入Q退出):")
if num=='Q':
exit()
num = format_out(num)
tmp = bracket(num)
num = format_out(tmp)
print(first_ans(num))