#_author: 10
#date: 2018/4/9 0009
#正则表达式实现计算器的一些基本功能
import re
def expression_islegal(source): #判断表达式是否合法
flag = True
if re.search("[a-zA-Z]", source): #表达式是否有字母
flag = False
else:
if source.count("(") != source.count(")"):
flag = False
return flag
def format(source): #对表达式进行格式化转换
source = source.replace("++", "+")
source = source.replace("--", "+")
source = source.replace("+-", "-")
source = source.replace("-+", "-")
source = source.replace("*+", "*")
source = source.replace("/+", "/")
source = source.replace(" ", "")
return source
#判断括号里的表达式是否有 *或者/号,有则进行分割
def mul_div(strs):
while re.search("[*/]", strs):
mul = re.search("-?\d+\.?\d*[*/]-?\d+\.?\d*",strs).group() #匹配乘除法以及包括符号的两个因子
#判断筛选出来的是乘法还是除法
if re.search("\*",mul):
x, y = mul.split("*")
if float(x)<0 and float(y)<0:
replace = "+" + str(float(x)*float(y))
else:
replace = str(float(x)*float(y))
elif re.search("\/", mul):
x, y = mul.split("/")
if float(x)<0 and float(y)<0:
replace = "+" + str(float(x)/float(y))
else:
replace = str(float(x)/float(y))
strs = strs.replace(mul, replace)
return strs
def add_sub(strs):
#先计算减法
while re.search("-?\d+\.?\d*-\d+\.?\d*", strs):
sub = re.search("-?\d+\.?\d*-\d+\.?\d*", strs).group()
if re.match("-", sub):
x, y, z = sub.split("-")
replace = str(-(float(y) + float(z)))
strs = strs.replace(sub, replace)
else :
x, y = sub.split("-")
replace = str((float(x) - float(y)))
strs = strs.replace(sub, replace)
#然后算加法
while re.search("-?\d+\.?\d*\+\d+\.?\d*", strs):
add = re.search("-?\d+\.?\d*\+\d+\.?\d*", strs).group()
if re.match("-", add):
x, y, z = re.split("[+-]", add)
replace = str((float(z) - float(y)))
strs = strs.replace(add, replace)
else :
x, y = add.split("+")
replace = str((float(x) + float(y)))
strs = strs.replace(add, replace)
return strs
#去括号
def find_bracket(fm_source):
strs = re.search("\([^()]+\)", fm_source).group() #(-9-2-5-2*3-5/3-40*4/2-3/5+6*3)
ret = mul_div(strs) #(-9-2-5-6.0-1.6666666666666667-80.0-0.6+18.0)
ret = add_sub(ret)
ret = ret.strip("()")
# ret = ret.replace("(", "")
# ret = ret.replace(")", "")
fm_source = fm_source.replace(strs, ret)
fm_source = format(fm_source)
return fm_source
#主程序入口
def cal():
#用户输入计算表达式
source = input("请输入:")#"1 - 2 * ( (60-30 +(-9-2-5-2*3-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"#输入计算表达式
#判断表达式是否合法
if not expression_islegal(source):
print("输入错误,请重新输入")
exit()
#对字符串进行格式化处理
fm_source = format(source)
#判断表达式是否有括号,有则进行去括号处理
while re.search("\(", fm_source):
fm_source = find_bracket(fm_source)
else:
mul_and_div = mul_div(fm_source)
add_and_sub = add_sub(mul_and_div)
result = add_and_sub
print(result)
if __name__ == "__main__":
cal()
通过用正则写一个简单的计算器发现好多方法都掌握的不好,任重而道远。