How to parse a string and return a nested array?

前端 未结 7 2193
你的背包
你的背包 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条回答
  •  时光说笑
    2020-11-30 08:38

    Using regex and ast.literal_eval

    >>> import re
    >>> from ast import literal_eval
    >>> def listit(t):
    ...         return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
    ... 
    def solve(strs):
        s = re.sub(r'[A-Za-z]', "'\g<0>',", strs)
        s = re.sub(r"\)", "\g<0>,", s)
        try: return listit( literal_eval('[' + s  + ']') )
        except : return "Invalid string! "
    ...     
    >>> solve("abc")
    ['a', 'b', 'c']
    >>> solve("a(b)c")
    ['a', ['b'], 'c']
    >>> solve("a(b(c))")
    ['a', ['b', ['c']]]
    >>> solve("a(b(c)")
    'Invalid string! '
    >>> solve("a)b(c")
    'Invalid string! '
    >>> solve("a(b))c")
    'Invalid string! '
    >>> solve('a((b(c))d)(e)')
    ['a', [['b', ['c']], 'd'], ['e']]
    

提交回复
热议问题