How to parse a string and return a nested array?

前端 未结 7 2194
你的背包
你的背包 2020-11-30 07:48

I want a Python function that takes a string, and returns an array, where each item in the array is either a character, or another array of this kind. Nested arrays are mark

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 08:48

    One rather quick and nasty approach (just for something different):

    import json, re
    
    def foo(x):
        # Split continuous strings
        # Match consecutive characters
        matches = re.findall('[a-z]{2,}', x)
        for m in matches:
            # Join with ","
            x = x.replace(m, '","'.join(y for y in list(m))) 
    
        # Turn curvy brackets into square brackets
        x = x.replace(')', '"],"')
        x = x.replace('(', '",["')
    
        # Wrap whole string with square brackets
        x = '["'+x+'"]'
    
        # Remove empty entries
        x = x.replace('"",', '')
        x = x.replace(',""', '')
    
        try:
            # Load with JSON
            return json.loads(x)
        except:
            # TODO determine error type
            return "error"
    
    def main():
        print foo("abc")     # ['a', 'b', 'c']
        print foo("a(b)c")   # ['a', ['b'], 'c']
        print foo("a(b(c))") # ['a', ['b', ['c']]]
        print foo("a(b))c")  # error
    
        print foo('a((b(c))d)(e)') # ['a', [['b', ['c']], 'd'], ['e']]
    

提交回复
热议问题