小编典典

Python解析括号中的块

python

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

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

最初应该返回:

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

将其作为输入应返回:

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

应该返回:

[ "{ c }" ]

[ "c" ]

[]

阅读 247

收藏
2020-12-20

共1个答案

小编典典

伪代码:

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.
2020-12-20