Python解析括号中的块 [英] Python parsing bracketed blocks

查看:71
本文介绍了Python解析括号中的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用Python解析匹配括号中包含的文本块的最佳方法是什么?

What would be the best way in Python to parse out chunks of text contained in matching brackets?

"{ { a } { b } { { { c } } } }"

最初应该返回:

[ "{ a } { b } { { { c } } }" ]

将其作为输入应返回:

[ "a", "b", "{ { c } }" ]

应返回:

[ "{ c }" ]

[ "c" ]

[]

推荐答案

伪代码:

For each string in the array:
    Find the first '{'. If there is none, leave that string alone.
    Init a counter to 0. 
    For each character in the string:  
        If you see a '{', increment the counter.
        If you see a '}', decrement the counter.
        If the counter reaches 0, break.
    Here, if your counter is not 0, you have invalid input (unbalanced brackets)
    If it is, then take the string from the first '{' up to the '}' that put the
     counter at 0, and that is a new element in your array.

这篇关于Python解析括号中的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆