![](/img/trans.png)
[英]How to recursively remove the first set of parantheses in string of nested parantheses? (in Python)
[英]Convert string with parantheses into nested list
我想這樣轉換一個字符串:
"asd foo bar ( lol bla ( gee bee ) lee ) ree"
到這樣的列表:
["asd","foo","bar",["lol","bla",["gee","bee"],"lee"],"ree"]
有一個簡單的解決方案嗎?
編輯:它應該適用於任何數量和深度的括號,但僅適用於有效的字符串(沒有單個括號)
edit2:空格可以看作是分隔符,如果不匹配,可能會引發錯誤或無法正常工作,我不在乎。 它僅適用於格式正確的字符串。
您可以使用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
!
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表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.