Rom*_*man 1 python string parsing
我有一个这样的字符串:'aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'
.从那个字符串我想得到以下结构:['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']
.换句话说,我想分开不同类型括号中的子串.
您需要使用堆栈方法来跟踪嵌套级别:
pairs = {'{': '}', '[': ']', '(': ')'}
def parse_groups(string):
stack = []
last = 0
for i, c in enumerate(string):
if c in pairs:
# push onto the stack when we find an opener
if not stack and last < i:
# yield anything *not* grouped
yield string[last:i]
stack.append((c, i))
elif c in pairs:
if stack and pairs[stack[-1][0]] == c:
# Found a closing bracket, pop the stack
start = stack.pop()[1]
if not stack:
# Group fully closed, yield
yield string[start:i + 1]
last = i + 1
else:
raise ValueError('Missing opening parethesis')
if stack:
raise ValueError('Missing closing parethesis')
if last < len(string):
# yield the tail
yield string[last:]
Run Code Online (Sandbox Code Playgroud)
这将生成组,如果需要,可以转换为列表:
>>> list(parse_groups('aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'))
['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']
Run Code Online (Sandbox Code Playgroud)
如果括号/括号不平衡,则会引发异常:
>>> list(parse_groups('aa(bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 19, in parse_groups
ValueError: Missing closing parethesis
>>> list(parse_groups('aa[{bb}}'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
>>> list(parse_groups('aa)bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
161 次 |
最近记录: |