将带括号的字符串转换为嵌套列表

3 投票
2 回答
1335 浏览
提问于 2025-04-17 09:07

我想把这样的字符串:

"asd foo bar ( lol bla ( gee bee ) lee ) ree"

转换成这样的列表:

["asd","foo","bar",["lol","bla",["gee","bee"],"lee"],"ree"]

有没有简单的方法可以做到这一点?

补充说明:这个方法应该能处理任意数量和深度的括号,但只需要适用于有效的字符串(不能有单独的括号)。

补充说明2:空格可以看作是分隔符,如果不匹配可能会报错或者直接不工作,我不在乎。只要能处理格式正确的字符串就行。

2 个回答

1

Pyparsing这个库自带了一个很方便的辅助方法,叫做nestedExpr

>>> from pyparsing import nestedExpr
>>> a = "asd foo bar ( lol bla ( gee bee ) lee ) ree"
>>> # have to put total string into ()'s
>>> printed nestedExpr().parseString("(%s)" % a).asList()[0]
['asd', 'foo', 'bar', ['lol', 'bla', ['gee', 'bee'], 'lee'], 'ree']

这里唯一需要注意的是,为了让解析器简单一些,整个字符串必须放在一对括号()里面。nestedExpr的默认分隔符是括号(),不过你也可以用其他成对的字符串或者pyparsing的表达式来替代。

9

你可以用Python的解析器来完成这个任务。只需要稍微帮一下它:

>>> a = "asd foo bar ( lol bla ( gee bee ) lee ) ree"
>>> eval(str(a.split()).replace("'(',", '[').replace("')'",']'))
['asd', 'foo', 'bar', ['lol', 'bla', ['gee', 'bee'], 'lee'], 'ree']

如果你想要更安全一点,可以用 ast.literal_eval 来代替哦!

撰写回答