【问题标题】:Turn a string with nested parenthesis into a nested list, python将带有嵌套括号的字符串转换为嵌套列表,python
【发布时间】:2014-06-04 19:37:42
【问题描述】:

在 Stack Overflow 上还有其他问题与此相关,例如 how-to-parse-a-string-and-return-a-nested-array?

但是它们都引用((abc)de(fg)))格式的列表。去表格:[['a','b','c']'d','e'['f','g',]]]我有表格列表:

((wordOneWord2)OtherWord(FinalWord)))

通过使用我从其他问题中学到的方法,嵌套列表的形式是:

[['w','o','r','d','O','n','e','W','o','r','d','2']'O','t','h','e','r','W','o','r','d',['F','i','n','a','l','W','o','r','d']]]

而不是想要的

[['wordOneWord2'], 'OtherWord', ['FinalWord']]

我可以通过逐个字母地解析列表然后将每个列表中的项目重新连接在一起来获得所需的结果,但是它需要的代码比我认为需要的要多,有没有更快的方法来做到这一点?

【问题讨论】:

    标签: python list parsing nested


    【解决方案1】:

    基于此solution by falsetru

    import re
    
    def parse_nested(text, left=r'[(]', right=r'[)]', sep=r','):
        """ Based on https://stackoverflow.com/a/17141899/190597 (falsetru) """
        pat = r'({}|{}|{})'.format(left, right, sep)
        tokens = re.split(pat, text)    
        stack = [[]]
        for x in tokens:
            if not x or re.match(sep, x): continue
            if re.match(left, x):
                stack[-1].append([])
                stack.append(stack[-1][-1])
            elif re.match(right, x):
                stack.pop()
                if not stack:
                    raise ValueError('error: opening bracket is missing')
            else:
                stack[-1].append(x)
        if len(stack) > 1:
            print(stack)
            raise ValueError('error: closing bracket is missing')
        return stack.pop()
    
    text = '((wordOneWord2)OtherWord(FinalWord))'
    print(parse_nested(text))
    # [[['wordOneWord2'], 'OtherWord', ['FinalWord']]]
    

    【讨论】:

      猜你喜欢
      • 2012-01-28
      • 2022-12-10
      • 1970-01-01
      • 2016-02-08
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      相关资源
      最近更新 更多