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

标签 python tree nltk parse-tree

我想获取 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())

关于python - 如何获取nltk树中某个节点的父节点和子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535591/

相关文章:

git - 重组 Git 存储库中的文件

c# - C# 标准库中的 B 树类?

python - 我如何评估我的技术?

python - 如何从文本文档中查找常用短语

java - 在 Java 中将单词转换为名词/形容词/动词形式

python - 如何使用 matplotlib 渲染 latex 矩阵

python - 在 TensorFlow Functional API 中保存和加载具有相同图表的多个模型

Python:过滤元组

html - 使用纯 HTML/CSS 创建树状图(多个父级)

python - 为什么 ax.patch 没有列在 plt.getp(ax) 的输出下?