【发布时间】:2015-04-04 19:04:40
【问题描述】:
我正在尝试打印 Penn Tree Bank 样式的解析,但我似乎无法正确平衡括号(令人沮丧 - 解析器运行良好,但我无法正确打印输出!)关于递归函数的任何提示或技巧可以做到这一点?
这是我当前的打印方法,我调用从解析的开始节点开始的函数。
def print_tree(current_node, parents, side):
print(parents)
for i in range(parents):
print(" ", " ", end="")
if current_node.is_terminal:
if side == 'left':
print("(" + current_node.lhs, current_node.word_label + " )")
else:
print("(" + current_node.lhs, current_node.word_label +")", "", end ="")
for i in range(parents):
print(")", "", end="")
print()
else:
print("( " +current_node.lhs)
if current_node.left_child != None:
print_tree(current_node.left_child, parents+1, 'left')
if current_node.right_child != None:
print_tree(current_node.right_child, parents+1, 'right')
我得到的结果:
( TOP
( S_VP
(VB 'List' )
( NP
( NP
(DT 'the' )
(NNS 'flights') ) ) ) ) )
( PP
( PP
(IN 'from' )
(NP_NNP 'Baltimore') ) ) ) ) ) )
( PP
(TO 'to' )
( NP
(NP_NNP 'Seattle' )
( NP
( NP
(DT 'that' )
(NN 'stop') ) ) ) ) ) ) ) ) )
( PP
(IN 'in' )
(NP_NNP 'Minneapolis') ) ) ) ) ) ) ) ) )
(PUNC '.') ) )
想要的结果:
( TOP
( S_VP
(VB 'List' )
( NP
( NP
(DT 'the' )
(NNS 'flights') )
( PP
( PP
(IN 'from' )
(NP_NNP 'Baltimore') )
( PP
(TO 'to' )
( NP
(NP_NNP 'Seattle' ))
( NP
( NP
(DT 'that' )
(NN 'stop') )
( PP
(IN 'in' )
(NP_NNP 'Minneapolis')))))
(PUNC '.') ) ))
我试图根据递归/缩进的次数来考虑一种方法,但没有取得太大的成功。
【问题讨论】: