我想在 nltk 树中获取节点的父节点和子节点。我在这里看到了这个答案,但我无法使其符合我的目的。
例如,拥有这棵树:
ROOT
|
S
_______|______________
| VP |
| ___|____ |
NP | ADJP |
| | ____|____ |
PRP VBZ RB JJ .
| | | | |
It is so nice .
我从其他答案中获取并修改了这段代码,这些答案提供了一些信息,但并不是我想要的。
ptree = ParentedTree.fromstring('(ROOT (S (NP (PRP It)) \
(VP (VBZ is) (ADJP (RB so) (JJ nice))) (. .)))')
leaf_values = ptree.leaves()
ptree.pretty_print()
if 'nice' in leaf_values:
leaf_index = leaf_values.index('nice')
print(leaf_index)
tree_location = ptree.leaf_treeposition(leaf_index)
print(tree_location)
print(ptree[tree_location])
print(tree_location[:-1])
print(ptree[tree_location[:-1]])
print(tree_location[:-2])
print(ptree[tree_location[:-2]])
3
(0, 1, 1, 1, 0)
nice
(0, 1, 1, 1)
(JJ nice)
(0, 1, 1)
(ADJP (RB so) (JJ nice))
我想实现以下内容。假设我的位置/节点“不错”。我想做一个函数,以便在输入“nice”的位置作为参数时获得“JJ”的位置。就像 get_parent(positionOf('nice')) 返回 positionOf('JJ')。然后我可以做 get_parent(positionOf('JJ')) 并返回 positionOf('ADJP') 等。
我还想获取一个节点的子节点,例如,如果我有 get_childs(positionOf('ADJP')) 它应该返回 position('RB') 和 positionOf('JJ')。
有人知道我该如何实现吗?你能提供一个小例子吗?