forked from magedu/python2016
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrule_parser.py
More file actions
105 lines (97 loc) · 3.1 KB
/
Copy pathrule_parser.py
File metadata and controls
105 lines (97 loc) · 3.1 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# #expr# & | ! ()
# (#e1# & #e2#) |(!#e3# & #e4#)
from stack import Stack
# '(#abc# & #324#) | (!#def# & #789#)'
def match(exprs, line, fn):
stack = Stack()
is_expr = False
expr = []
for c in exprs:
if c == '#':
if not is_expr:
is_expr = True
else:
is_expr = False
v = fn(line, ''.join(expr))
expr = []
if stack.top is None:
stack.push(v)
continue
s = stack.pop()
if s == '!':
v = not v
if stack.top is None:
stack.push(v)
continue
s = stack.pop()
if s == '&':
if isinstance(stack.top.value, bool):
v = stack.pop() and v
stack.push(v)
else:
raise Exception('wrong expr')
elif s == '|':
if isinstance(stack.top.value, bool):
v = stack.pop() or v
stack.push(v)
else:
raise Exception('wrong expr')
elif s == '(':
stack.push(s)
stack.push(v)
else:
raise Exception('wrong expr')
else:
if is_expr:
expr.append(c)
else:
if c in '(&!|':
stack.push(c)
elif c.strip() == '':
pass
elif c == ')':
v = stack.pop()
if not isinstance(v, bool):
raise Exception('wrong expr')
s = stack.pop()
if s == '!':
v = not v
s = stack.pop()
if s == '(':
stack.push(v)
else:
raise Exception('wrong expr')
else:
raise Exception('wrong expr')
while stack.top:
v = stack.pop()
if not isinstance(v, bool):
raise Exception('wrong expr')
s = stack.pop()
if s == '!':
v = not v
s = stack.pop()
if s == '&':
v2 = stack.pop()
if not isinstance(v2, bool):
raise Exception('wrong expr')
v = v and v2
elif s == '|':
v2 = stack.pop()
if not isinstance(v2, bool):
raise Exception('wrong expr')
v = v or v2
else:
raise Exception('wrong expr')
if stack.top is None:
return v
else:
stack.push(v)
if __name__ == '__main__':
import re
line = 'abc 123 def 456 asd 789'
exprs = '(#abc# & #324#) | (!#def# & #789#)' # False
def callback(line, expr):
return re.match(expr, line) is not None
print(match(exprs, line, callback))
#TODO 优化两个程序, 使其模块化