Turn a string with nested parenthesis into a nested list, python(将带有嵌套括号的字符串转换为嵌套列表,python)
问题描述
在 Stack Overflow 上还有其他相关问题,例如 如何解析字符串并返回嵌套数组?
There are other questions referring to this on Stack Overflow such as how-to-parse-a-string-and-return-a-nested-array?
但它们都是以((abc)de(fg)))格式引用列表.转到表格:[['a','b','c']'d','e'['f','g',]]] 我有一个列表形式:
But they all refer to lists in the format of ((abc)de(fg))). going to the form:[['a','b','c']'d','e'['f','g',]]]  I have a list of the form:
((wordOneWord2)OtherWord(FinalWord)))
通过使用我从嵌套列表的其他问题中学到的方法,形式为:
By using the methods I learnt from the other questions by nested list was of the form:
[['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']]
我可以通过逐个字母解析列表然后将每个列表中的项目重新连接在一起来获得所需的结果,但它需要的代码比我认为需要的要多,有没有更快的方法?
I can achieve the desired result by parsing the list letter by letter and then concatenating the items within each list back together but it takes more code than I think necessary, is there a faster way of doing this?
推荐答案
基于此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']]]
                        这篇关于将带有嵌套括号的字符串转换为嵌套列表,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将带有嵌套括号的字符串转换为嵌套列表,pyth
				
        
 
            
        基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 包装空间模型 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				