運用正則表達式不使用內置方法實現計算器


#__author__:"Jay guo"
#__date__:2016/9/12
import re
def check(s):
if re.findall("[a-zA-Z]",s):
return "quit"
else:
return s

def format(s):
s = s.replace(" ","")
s = s.replace("++","+")
s = s.replace("+-","-")
s = s.replace("-+","-")
s = s.replace("--","+")
return s

def mul_exc(s):
while True:
ret = re.search("\d+\.?\d*[*/][+-]?\d+\.?\d*", s)
if ret:
x,y = re.split("[*/]",ret.group())
x = float(x)
y = float(y)
if "*" in ret.group():
end = x*y
else:
end = x/y
s = s.replace(ret.group(),str(end))
else:
break
return s

def add_sub(s):
while True:
ret = re.search("\d+\.?\d*[+-]\d+\.?\d*", s)
if ret:
x,y = re.split("[+-]", ret.group())
x = float(x)
y = float(y)
if "+" in ret.group():
end = x + y
else:
end = x - y
s = s.replace(ret.group(), str(end))
else:
break
s = s.replace("(","")
s = s.replace(")","")
return s

def main():
while True:
user = input("PLZ input>>>>: ")
user = check(user)
if user == "quit":
print ("False")
continue
user = format(user)
user = "(" + user + ")"
while True:
ret = re.search("\([^()]*\)",user)
if ret:
ret = ret.group()
ret1 = mul_exc(ret)
ret1 = add_sub(ret1)
user = user.replace(ret,ret1)
user = format(user)
else:
user = add_sub(user)
break
print("結果",user)

main()

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com