我想在nltk树中获取节点的父节点和子节点。我已经看到了这个答案here但我无法适应我的目的。
例如,拥有这棵树:
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'))它应该返回位置('RB')和positionOf('JJ')。
有人知道我怎么能实现它?你能提供一个小例子吗?
叶子的父级:print(ptree [tree_location [: - 1]]。label())
第一个祖先:print(ptree [tree_location [: - 2]]。label())