python嵌套列表法实现树_python – 将嵌套的括号树转换为嵌套列表
我有一個樹結(jié)構(gòu)文件,其中括號用于表示樹.這是將代碼轉(zhuǎn)換為
python嵌套列表的代碼
def foo(s):
def foo_helper(level=0):
try:
token = next(tokens)
except StopIteration:
if level != 0:
raise Exception('missing closing paren')
else:
return []
if token == ')':
if level == 0:
raise Exception('missing opening paren')
else:
return []
elif token == '(':
return [foo_helper(level+1)] + foo_helper(level)
else:
return [token] + foo_helper(level)
tokens = iter(s)
return foo_helper()
當字符長度為1時,它工作正常.對于單詞或句子,同樣不適當?shù)墓ぷ?
我的樹樣本是:
( Satellite (span 69 74) (rel2par Elaboration)
( Nucleus (span 69 72) (rel2par span)
( Nucleus (span 69 70) (rel2par span)
( Nucleus (leaf 69) (rel2par span) (text _!MERRILL LYNCH READY ASSETS TRUST :_!) )
( Satellite (leaf 70) (rel2par Elaboration) (text _!8.65 % ._!) )
)
( Satellite (span 71 72) (rel2par Elaboration)
( Nucleus (leaf 71) (rel2par span) (text _!Annualized average rate of return_!) )
( Satellite (leaf 72) (rel2par Temporal) (text _!after expenses for the past 30 days ;_!) )
)
)
( Satellite (span 73 74) (rel2par Elaboration)
( Nucleus (leaf 73) (rel2par span) (text _!not a forecast_!) )
( Satellite (leaf 74) (rel2par Elaboration) (text _!of future returns ._!) )
)
)
在這里,輸出需要
[‘satellite’,[‘span’,’69’,’74’] ………]但是給定的函數(shù)我得到的是[‘s’,’a’,’t’. ………….. [ ‘S’, ‘p’, ‘A’, ‘N’, ‘7’, ‘3’] ……….. …]
怎么修改?
最佳答案 我以為你想用_!來表示帶空格的字符串.然后我使用正則表達式拆分表達式:
from re import compile
resexp = compile(r'([()]|_!)')
…
tokens = iter(resexp.split(s))
…
我的結(jié)果是(使用深度= 4的pprint)
$python lispparse.py | head
['\n',
[' Satellite ',
['span 69 74'],
' ',
['rel2par Elaboration'],
'\n ',
[' Nucleus ',
['span 69 72'],
' ',
['rel2par span'],
我進一步改進了它:
tokens = iter(filter(None, (i.strip() for i in resexp.split(s))))
得到了:
$python lispparse.py
[['Satellite',
['span 69 74'],
['rel2par Elaboration'],
['Nucleus',
['span 69 72'],
['rel2par span'],
['Nucleus', [...], [...], [...], [...]],
['Satellite', [...], [...], [...], [...]]],
['Satellite',
['span 73 74'],
['rel2par Elaboration'],
['Nucleus', [...], [...], [...]],
['Satellite', [...], [...], [...]]]]]
總結(jié)
以上是生活随笔為你收集整理的python嵌套列表法实现树_python – 将嵌套的括号树转换为嵌套列表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql的代码需要保存吗_php向My
- 下一篇: 如何用python做计算软件_如何用Py