简体   繁体   English

如何访问NLTK树中节点的内容?

[英]How can I access the contents of a node in a NLTK tree?

I am trying to search for a POS tag based on a word using NLTK Tree. 我正在尝试使用NLTK树基于单词搜索POS标签。

I want to locate a word (here: different) in the tree (the word is definitely present in the tree), and check if any of the children of the node containing this word has a given label (here: NN). 我想在树中找到一个词(这里:不同)(该词肯定存在于树中),并检查包含该词的节点的任何子代是否具有给定标签(这里:NN)。

from nltk.tree import Tree

input_string = '(ROOT (SBARQ (WHADVP (WRB How)) (SQ (VBZ is) (NP (PRP it)) (ADJP (JJ different) (PP (IN from) (NP (DT the) (JJ dishonest) (NNS businessmen))))) (. ?)))'
for t in Tree.fromstring(input_string, read_node=lambda s: '<%s>' % s, read_leaf=lambda s: '"%s"' % s):
    print (t)

I tried to go through the documentation, but I am unable to get any further than this. 我试图浏览文档,但是我无法获得更多的信息。

What I am trying to do is : 我想做的是:

if t.leaves() in ["different"]:
    if content_of_t (I don't know how to access that) in ["NN"]:
        return "yes"

You can walk through all subtrees of the tree. 您可以遍历树的所有子树。

tree = Tree.fromstring(
           input_string, 
           read_node=lambda s: '<%s>' % s,
           read_leaf=lambda s: '%s' % s)

for sub_tree in tree.subtrees(): 
    if sub_tree.label()  == '<JJ>' and 'different' in set(sub_tree.leaves()):
        print('yes')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM