1. 程式人生 > >初學re模塊--簡易計算器

初學re模塊--簡易計算器

re.search () ont style spl replace else nth repl

import re
import time
print("請輸入需要計算的公式:")
source = input()
t1=time.time()
# source=‘6+7/(5-4*3/2+23)‘
def check(s):
flag = True
if re.search(‘[a-z]‘, s):
flag = False
if re.search(‘[A-Z]‘, s):
flag = False
if re.search(‘\.{2,}‘, s):
flag = False
if re.search(‘\*{2,}‘, s):
flag = False
if re.search(‘\+{2,}‘, s):
flag = False
if re.search(‘-{2,}‘, s):
flag = False
if s.count(‘(‘)!= s.count(‘)‘):
flag = False
return flag

def fmat(s):
s=s.replace(‘ ‘, ‘‘)
s=s.replace(‘++‘,‘+‘)
s=s.replace(‘+-‘,‘-‘)
s=s.replace(‘-+‘,‘-‘)
return s

def mul(s):
s1=re.search(‘\d+\.?\d*\*-?\d+\.?\d*‘,s).group()
s2=re.split(‘\*‘,s1)
s=s.replace(s1,str(float(s2[0])*float(s2[1])))
return s

def div(s):
s1=re.search(‘\d+\.?\d*/-?\d+\.?\d*‘,s).group()
s2=re.split(‘/‘,s1)
s=s.replace(s1,str(float(s2[0])/float(s2[1])))
return s

def add(s):
if s[0]==‘-‘:
s1=re.match(‘-\d+\.?\d*\+\d+\.?\d*‘,s).group()
s2=re.split(‘-‘,s1)
s3=re.split(‘\+‘,s2[1])
s=s.replace(s1,str(float(s3[1])-float(s3[0])))
else:
s1 = re.match(‘\d+\.?\d*\+\d+\.?\d*‘, s).group()
s3 = re.split(‘\+‘, s1)
s = s.replace(s, str(float(s3[1])+float(s3[0])))
return s

def sub(s):
if s[0]==‘-‘:
s1=re.match(‘-\d+\.?\d*-\d+\.?\d*‘,s).group()
s2=s1[1:-1]
s3=re.split(‘-‘,s2)
s=s.replace(s1,str(-float(s3[1])-float(s3[0])))
else:
s1 = re.match(‘\d+\.?\d*-\d+\.?\d*‘, s).group()
s3 = re.split(‘-‘, s1)
s = s.replace(s1,str(float(s3[0])-float(s3[1])))
return s

def remove_paranthesis(s):
s1=re.split(‘\(‘,s)
s2=re.split(‘\)‘,s1[1])
return s2[0]

if check(source):
source = fmat(source)#格式化輸出
ret=source
while ret.count(‘(‘) > 0:#有括號
ret0= re.search(‘\([^()]+\)‘, ret).group()#判斷最內層括號
ret1=ret0
while ‘*‘in ret1 :#判斷乘除法
ret1=mul(ret1)
while ‘/‘in ret1:
ret1=div(ret1)
else:
ret1=fmat(ret1)
ret1 = ret1.replace(ret1, remove_paranthesis(ret1))
while ‘+‘in ret1 or ‘-‘in ret1:
ret2=re.search(‘\d+\.?\d*[+\-]\d+\.?\d*‘,ret1).group()
if ‘+‘in ret2:
ret1=add(ret1)
if ‘-‘in ret2:
ret1=sub(ret1)
else:
ret=ret.replace(ret0,ret1)
else:
while ‘*‘in ret:#判斷乘除法
ret=mul(ret)
while ‘/‘in ret:
ret=div(ret)
else:
ret=fmat(ret)
while ‘+‘in ret or ‘-‘in ret:
ret2=re.search(‘\d+\.?\d*[+\-]\d+\.?\d*‘,ret).group()
if ‘+‘in ret2:
ret=add(ret)
if ‘-‘in ret2:
ret=sub(ret)
else:
print(ret)
print(time.time()-t1)

初學re模塊--簡易計算器