#!/usr/bin/python
#_*_ coding:utf-8 _*_
#Author:LiuJindong
#datetime:2018/9/19 10:50
import re
def check_expression(s):
#此函数用于判断公式是否符合规则
flag=True
# 判断公式中括号是否对称出现
if not s.count('(')==s.count(')'):
print('\033[31;1m表达式中少括号.\033[0m')
flag=False
# 判断公式中是否有字母
if re.findall(r'[a-z]',s.upper()):
print('\033[31;1m表达式中有字母.\033[0m')
flag=False
return flag
def format_string(s):
#此函数用于处理表达式中不规范部分
s=s.replace(' ', '')
s=s.replace('--','+')
s=s.replace('++','+')
s=s.replace('-+','-')
s=s.replace('+-','-')
s=s.replace('+*','*')
s=s.replace('*+','*')
s=s.replace('/+','/')
s=s.replace('+/','/')
return s
def calc_mul_div(s):
#此函数用于计算乘除
# 用于匹配表达式中是否包含乘法和除法
regular=r'[\-]?\d+\.?\d*([*/])[\-]?\d+\.?\d*'
while re.findall(regular,s):
#获取表达式
expression=re.search(regular,s).group()
#处理乘法
if expression.count('*')==1:
#获取要计算的两个数字
x,y=expression.split('*')
#计算结果
mul_res='+'+str(float(x)*float(y))
#把计算结果替换为表达式
s=s.replace(expression,mul_res)
#把表达式不规范+、-、*、/格式化一下
s=format_string(s)
#处理除法
if expression.count('/')==1:
#获取要计算的两个数字
x,y=expression.split('/')
#计算结果
div_res='+'+str(float(x)/float(y))
#把计算结果替换为表达式
s=s.replace(expression,div_res)
#格式化表达式
s=format_string(s)
return s
def calc_add_sub(s):
#此函数用于计算加减
#匹配加法正则表达式
add_regular=r'[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*'
#匹配减法正则表达式
sub_regular=r'[\-]?\d+\.?\d*\-[\-]?\d+\.?\d*'
#处理加法
while re.findall(add_regular,s):
#把获取到加法添加到列表中
add_list=re.findall(add_regular,s)
#遍历所有的加法
for add_str in add_list:
x,y=add_str.split('+')
add_res='+'+str(float(x)+float(y))
s=s.replace(add_str,add_res)
s=format_string(s)
#处理减法
while re.findall(sub_regular,s):
#把获取到减法添加到列表中
sub_list=re.findall(sub_regular,s)
#遍历所有的减法
for sub_str in sub_list:
numbers=sub_str.split('-')
if len(numbers)==3:
sub_res=0
for v in numbers:
if v:
sub_res-=float(v)
else:
x,y=numbers
sub_res=float(x)-float(y)
s=s.replace(sub_str,'+'+str(sub_res))
s=format_string(s)
return s
if __name__=='__main__':
data=input('请输入>>>:')
#判断输入的公式是否符合标准
if check_expression(data):
#把公式格式化一下
data=format_string(data)
print(data)
#通过eval方式计算结果,方便后面对比.
print('Eval result:', eval(data))
#判断公式中包含括号的情况
while data.count('(')>0:
#获取最内部括号
strs=re.search(r'\([^()]*\)',data).group()
#计算乘除
replace_strs=calc_mul_div(strs)
#计算加、减
replace_strs=calc_add_sub(replace_strs)
data=format_string(data.replace(strs,replace_strs[1:-1]))
else:
replace_strs=calc_mul_div(data)
replace_strs=calc_add_sub(replace_strs)
data=data.replace(data,replace_strs)
print('Calc result:',data.replace('+',''))