簡體   English   中英

將帶有嵌套括號的字符串轉換為嵌套列表python

[英]Turn a string with nested parenthesis into a nested list, python

在Stack Overflow上還有其他問題,例如how-to-parse-a-string-and-return-a -ested-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']]

我可以通過逐字母解析列表然后將每個列表中的項目連接在一起來實現所需的結果,但是它需要的代碼比我認為的要多,有沒有更快的方法呢?

基於此解決方案,由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']]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM