Python-正则表达式实现计算器功能

需求:

用户输入运算表达式,终端显示计算结果

源代码:

 1 # !/usr/bin/env/ python3
 2 # -*- coding: utf-8 -*-
 3 
 4 """用户输入计算表达式,显示计算结果"""
 5 
 6 __author__ = 'Jack'
 7 
 8 import re
 9 
10 bracket = re.compile(r'([^()]+)')  # 寻找最内层括号规则
11 mul = re.compile(r'(d+.?d**-d+.?d*)|(d+.?d**d+.?d*)')  # 寻找乘法运算规则
12 div = re.compile(r'(d+.?d*/-d+.?d*)|(d+.?d*/d+.?d*)')  # 寻找除法运算规则
13 add = re.compile(r'(-?d+.?d*+-d+.?d*)|(-?d+.?d*+d+.?d*)')  # 寻找加法运算规则
14 sub = re.compile(r'(-?d+.?d*--d+.?d*)|(-?d+.?d*-d+.?d*)')  # 寻找减法运算规则
15 c_f = re.compile(r'(?+?-?d+)?')  # 检查括号内是否运算完毕规则
16 strip = re.compile(r'[^(].*[^)]')  # 脱括号规则
17 
18 
19 def Mul(s):
20     """计算表达式中的乘法运算"""
21     exp = re.split(r'*', mul.search(s).group())
22     return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1])))
23 
24 
25 def Div(s):
26     """计算表达式中的除法运算"""
27     exp = re.split(r'/', div.search(s).group())
28     return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1])))
29 
30 
31 def Add(s):
32     """计算表达式中的加法运算"""
33     exp = re.split(r'+', add.search(s).group())
34     return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1])))
35 
36 
37 def Sub(s):
38     """计算表达式中的减法运算"""
39     exp = sub.search(s).group()
40     if exp.startswith('-'):                 #如果表达式形如:-2.2-1.2;需变换为:-(2.2+1.2)
41         exp = exp.replace('-', '+')         #将-号替换为+号;+2.2+1.2
42         res = Add(exp).replace('+', '-')    #调用Add运算,将返回值+3.4变为-3.4
43     else:
44         exp = re.split(r'-', exp)
45         res = str(float(exp[0]) - float(exp[1]))
46     return s.replace(sub.search(s).group(), res)
47 
48 
49 def calc():
50     while True:
51         s = input('Please input the expression(q for quit):')  # 例:'1+2- (3*  4-3/2+ (   3-2*(3+  5 -3*  -0.2-3.3*2.2 -8.5/ 2.4 )+10) +10)'
52         if s == 'q':
53             break
54         else:
55             s = ''.join([x for x in re.split('s+', s)])  # 将表达式按空格分割并重组
56             if not s.startswith('('):  # 若用户输入的表达式首尾无括号,则统一格式化为:(表达式)
57                 s = str('(%s)' % s)
58             while bracket.search(s):  # 若表达式s存在括号
59                 s = s.replace('--', '+')  # 检查表达式,并将--运算替换为+运算
60                 s_search = bracket.search(s).group()  # 将最内层括号及其内容赋给变量s_search
61                 if div.search(s_search):  # 若除法运算存在(必须放在乘法之前)
62                     s = s.replace(s_search, Div(s_search))  # 执行除法运算并将结果替换原表达式
63                 elif mul.search(s_search):  # 若乘法运算存在
64                     s = s.replace(s_search, Mul(s_search))  # 执行乘法运算并将结果替换原表达式
65                 elif sub.search(s_search):  # 若减法运算存在(必须放在加法之前)
66                     s = s.replace(s_search, Sub(s_search))  # 执行减法运算并将结果替换原表达式
67                 elif add.search(s_search):  # 若加法运算存在
68                     s = s.replace(s_search, Add(s_search))  # 执行加法运算并将结果替换原表达式
69                 elif c_f.search(s_search):  # 若括号内无任何运算(类似(-2.32)除外)
70                     s = s.replace(s_search, strip.search(s_search).group())  # 将括号脱掉,例:(-2.32)---> -2.32
71 
72             print('The answer is: %.2f' % (float(s)))
73 
74 if __name__ == '__main__':
75     calc()
使用正则表达式实现计算器功能

运行效果:

原文地址:https://www.cnblogs.com/OldJack/p/6781704.html