给定以下解析树:
在:
from nltk.parse import CoreNLPParser
from nltk.treeprettyprinter import TreePrettyPrinter
parser = CoreNLPParser(url='http://localhost:9000')
next(parser.raw_parse('What is the airspeed of an unladen swallow ?')).pretty_print()退出:
ROOT
|
SBARQ
__________________________|____________________________
| SQ |
| ___|_________________ |
| | NP |
| | _____________|______________________ |
| | | PP S |
| | | ____|___ | |
WHNP | NP | NP VP |
| | ___|_____ | ___|_____ | |
WP VBZ DT NN IN DT JJ VB .
| | | | | | | | |
What is the airspeed of an unladen swallow ? 有和不带终端节点的按预定顺序遍历它的正确方法是什么?
到目前为止,我的主要问题是我不知道如何遍历树。当我这么做时:
for e in parse_tree:
print(e)我得到:
(ROOT
(SBARQ
(WHNP (WP What))
(SQ
(VBZ is)
(NP
(NP (DT the) (NN airspeed))
(PP (IN of) (NP (DT an) (JJ unladen)))
(S (VP (VB swallow)))))
(. ?)))换句话说,我不能访问每一棵树的枝条。通过这种结构的正确方法是什么?
发布于 2022-11-22 06:44:13
根据你的描述,‘空载燕子的空速是多少?'。如果我是对的,我想你一直想要叶节点。!您应该应用DFS(preorder),这将给出树的输出叶节点。
代码-:打印叶节点
leafnodes=[]
def leafnode(node):
if not node:
return
if not node.left and not node.right:
leafnodes.append(node.val)
leafnode(node.left)
leafnode(node.right)
leafnode(root)
print(leafnodes)https://stackoverflow.com/questions/71690744
复制相似问题