本文实例讲述了Python3.6基于正则实现的计算器。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# -*- coding:utf-8 -*-
#!python3
import re
import copy
def my_calc(inside):
"""
计算括号内的算术式
:param inside:算术式
:return:结果
"""
while True :
# 1、首先需要把含有优先级最高的*和/找出来
# 这里有几种情况,(1*1) (1*-1) (-1*1)除法类似(暂时不考虑分母为0的情况)
# 但是有了正则就方便多了
search_ret = re.search( '(\(-)?\d+(\.\d+)?[*/]-?\d+(\.\d+)?' , inside)
if search_ret is None :
break
ret_str = search_ret.group()
if '(' in ret_str:
ret_str = ret_str[ 1 :]
num_list = re.split( '[*/]' , ret_str)
operator = re.search( '[*/]' , ret_str).group()
calc_ret = 0
if operator = = '*' :
calc_ret = float (num_list[ 0 ]) * float (num_list[ 1 ])
elif operator = = '/' :
calc_ret = float (num_list[ 0 ]) / float (num_list[ 1 ])
inside = inside.replace(ret_str, str (calc_ret))
# */都运算完以后就可以做+-了
while True :
# 2、把含有+-的算术式找出来
search_ret = re.search( '(\(-)?\d+(\.\d+)?[+\-]-?\d+(\.\d+)?' , inside)
if search_ret is None :
break
ret_str = search_ret.group()
if '(' in ret_str:
ret_str = ret_str[ 1 :]
tmp_str = copy.copy(ret_str)
num_1 = re.match( '-?\d+(\.\d+)?' , tmp_str).group()
tmp_str = tmp_str.replace(num_1, '')
operator = tmp_str[ 0 ]
num_2 = tmp_str[ 1 :]
calc_ret = 0
if operator = = '+' :
calc_ret = float (num_1) + float (num_2)
elif operator = = '-' :
calc_ret = float (num_1) - float (num_2)
inside = inside.replace(ret_str, str (calc_ret))
return re.sub( '[()]' , '', inside)
def format_str(s):
s = s.replace( '--' , '+' )
s = s.replace( '-+' , '-' )
s = s.replace( '++' , '+' )
s = s.replace( '+-' , '-' )
if s[ 0 ] = = '+' :
s = s[ 1 :]
s = '(' + s + ')'
return s
def un_bracket_calc(final_str): # -1*2+3-4/-5
final_str = format_str(final_str)
final_str = my_calc(final_str)
return final_str
def my_math(s): # "((-1-2*-3)/(3-2)+(9*5-89)*(2*3*(3-0)))"
while True :
inside_bracket = re.search( '[()]+[()]+' , s)
if inside_bracket is None :
# 括号都算完了,如果还有算术式继续运算
s = un_bracket_calc(s)
break
src_str = inside_bracket.group()
ret = my_calc(src_str)
s = s.replace(src_str, ret)
return s
s_src = "((-1 - 2 * -3) / (3 - 2) + (9 * 5 - 9) * (2 * 3 * (3 - 0))) * -100 + 99-100 * -1-1"
s_src = s_src.replace( ' ' , '')
print (my_math(s_src))
s_ret = (( - 1 - 2 * - 3 ) / ( 3 - 2 ) + ( 9 * 5 - 9 ) * ( 2 * 3 * ( 3 - 0 ))) * - 100 + 99 - 100 * - 1 - 1
print (s_ret)
|
运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/tyrantu1989/article/details/78473637