Skip to main content
 首页 » 编程设计

python之如何获取nltk树中某个节点的父节点和子节点

2025年05月04日13shangdawei

我想获取 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') 等。

我还想获得一个节点的 child ,例如,如果我有 get_childs(positionOf('ADJP')) 它应该返回 position('RB') 和 positionOf('JJ')。

有人知道我该如何实现吗?你能举个小例子吗?

请您参考如下方法:

叶子的父级: 打印(ptree[tree_location[:-1]].label())

始祖: 打印(ptree[tree_location[:-2]].label())