Skip to main content
 首页 » 编程设计

python之是否有一个简单的 Python 字符串解析器

2025年05月04日25zhujiabin

我有一个这样的字符串:'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:] 

这将生成组,如果您需要,可以将其转换为列表:

>>> list(parse_groups('aaa(cc(kkk)c)ddd[lll]{m(aa)mm}')) 
['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}'] 

如果方括号/圆括号不平衡,则抛出异常:

>>> 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