Python parsing bracketed blocks

后端 未结 9 1939
独厮守ぢ
独厮守ぢ 2020-11-27 04:44

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

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

should i

9条回答
  •  轮回少年
    2020-11-27 05:06

    Pseudocode:

    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.
    

提交回复
热议问题