本文我们实现表达式字符串的格式化。

要得到的格式

设想一下我们要输入的表达式字符串是:

1
(* 2 (+ 3 4 (- 1 2)) 5)

而我们的目标格式是一个 list

1
[* 2 [+ 3 [1 2]] 5] 

以下是解析代码:

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
class ExpressionFormattor:
def format(self,exp):
if exp.isdigit() or (exp.find("'") != -1 or exp.find('"') != -1) or (exp.find("(") == -1 and exp.find(")") == -1):
return exp
exp = exp.replace("\n"," ")
return self._convert_to_list(exp)
def _convert_to_list(self,exp):
if exp.find("(") == -1:
return exp != "" and [exp] or []
exp_list = []
word = ""
i = 1
while i < len(exp)-1:
if exp[i].isspace():
if word != "":
exp_list.append(word)
word = ""
i += 1
elif exp[i] == "'":
i += 1
elif exp[i] == "(":
right_par_index = self._find_right_parenthesis(exp,i)
exp_list.append(self._convert_to_list(exp[i:right_par_index+1]))
i = right_par_index + 1
else:
word += exp[i]
i += 1
if word != "":
exp_list.append(word)
return exp_list
def _find_right_parenthesis(self,exp,left_index):
count = 0
for i in range(left_index,len(exp) - 1):
if exp[i] == "(":
count += 1
elif exp[i] == ")":
count -= 1
if count == 0:
return i
return -1