Python写的计算器程序(主要目的在于熟悉下正则表达式)

2021-06-26 20:05

阅读:643

import re
s = ‘1-2*((60-30-(-40/5)*(9-2*5/3-7/3*99/4*2998-10*568/14.3))+(-4*3)/16-3)‘
s2 = 1-2*((60-30-(-40/5)*(9-2*5/3-7/3*99/4*2998-10*568/14.3))+(-4*3)/16-3)
def check(s):#字符检错,不合法就返回False
flag = True
s = re.sub(‘ ‘,‘‘,s)#去空格
if re.findall(‘[^\d+\-*/.()]‘,s):#检测出常规计算字符外的其他字符
print(‘存在非法字符‘)
flag = False
elif re.findall(‘(\.\d\.)|(\D\.\D)|(\d\.\D)|(\D\.\d)‘,s):#检查出错误的小数
print(‘存在小数格式异常‘)
flag = False
elif re.findall(‘[*/+\-]+[*/+\-]+|.[*/+\-]\)‘,s):#判断计算符号输入是否异常
print(‘计算符号有误‘)
flag = False
if flag == False:
s = None
return s

def jisuan1(string):
if re.findall(‘[()]‘,string):#有括号的处理方式
string = re.sub(‘[()]‘,‘‘,string)
while True:
string.replace(‘+-‘,‘-‘)
string.replace(‘-+‘, ‘-‘)
string.replace(‘--‘, ‘+‘)
try:
x = re.search(‘[\-]*(?:\d+\.\d*|\d*)[*/](?:\d+\.\d*|\d*)‘,string).group()
if ‘*‘ in x:
y = float(x[:x.index(‘*‘)]) * float(x[x.index(‘*‘)+1:])
string = string.replace(x,str(y))
else:
y = float(x[:x.index(‘/‘)]) / float(x[x.index(‘/‘) + 1:])
string = string.replace(x, str(y))
except :
try:
x = re.search(‘[\-]*(?:\d+\.\d*|\d+)[+\-](?:\d+\.\d*|\d+)‘, string).group()
if ‘+‘ in x:
y = float(x[:x.index(‘+‘)]) + float(x[x.index(‘+‘) + 1:])
string = string.replace(x, str(y))
else:
if x.count(‘-‘) >1:
y = float(‘‘.join([‘-‘,x.split(‘-‘)[1]])) + float(‘‘.join([‘-‘,x.split(‘-‘)[2]]))
string = string.replace(x, str(y))
else:
y = float(x[:x.index(‘-‘)]) - float(x[x.index(‘-‘) + 1:])
string = string.replace(x, str(y))
except Exception as e:
raise e
if re.findall(‘[\-]*(?:\d+\.\d*|\d+)[+\-*/](?:\d+\.\d*|\d+)‘,string) == []:
break
return string

def jisuan2(s):#获取括号里的内容,并加以计算
if s != None:
while True:
k = re.findall(‘(?:\d+\.\d*|\d+)[*/][\-+]+(?:\d+\.\d*|\d+)‘,s)
for j in k:
if ‘+‘ in j:
s = s.replace(j,j.replace(‘+‘,‘‘))
else:
s = s.replace(j, ‘‘.join([‘-‘, j.replace(‘-‘, ‘‘)]))
s = s.replace(‘--‘, ‘+‘)
s = s.replace(‘+-‘, ‘-‘)
s = s.replace(‘-+‘, ‘-‘)
try:
x = re.search(‘\([^()]+\)‘,s).group()#得到最里层括号的内容
a = jisuan1(x) # 将内容计算出来
s = s.replace(x, a) # 将计算结果与之前的内容置换
except Exception as e:
a = jisuan1(s) # 将内容计算出来
s = a # 将计算结果与之前的内容置换
if re.findall(‘[\-]*(?:\d+\.\d*|\d+)[+\-*/](?:\d+\.\d*|\d+)‘, s) == []:
break
return s
#
a = check(s)
print(‘代码结果:‘,jisuan2(a))
print(‘正确结果:‘,s2)



评论


亲,登录后才可以留言!