(1)我的目标:提取产品的左侧和右侧。如何从tree.productions中提取元素()
(2)我的方法: 我正在使用斯坦福分析器和nltk工具来提取句子的分析树。我的代码如下:“NP VP”
corenlp_dir = "/home/corenlp-python/stanford-corenlp-full-2013-11-12/"
parser = corenlp.StanfordCoreNLP(corenlp_path=corenlp_dir)
result_json = json.loads(parser.parse("I have a tree."))
for sentence in result_json["sentences"]:
t = Tree.fromstring(sentence["parsetree"])
print t.productions() # [ROOT -> S, S -> NP VP ., NP -> PRP, PRP -> 'I', VP -> VBP NP, VBP -> 'have', NP -> DT NN, DT -> 'a', NN -> 'tree', . -> '.']
print t.productions()[1] # S -> NP VP .
print type(productions()[1]) # <class 'nltk.grammar.Production'>
for (i,child) in enumerate(t):
print (i,child) # (0, Tree('S', [Tree('NP', [Tree('PRP', ['I'])]), Tree('VP', [Tree('VBP', ['have']), Tree('NP', [Tree('DT', ['a']), Tree('NN', ['tree'])])]), Tree('.', ['.'])])) I can only get one tree.
(3)我的问题是如何能够继续提取从每个生产的两侧的元件,如“S”和。有什么方法可以用来解决这个问题吗?
任何人都可以帮助我,也许指出一些方向?
你为什么使用'productions'方法?这听起来像你真正想要做的就是遍历树。查看['productions'方法](http://www.nltk.org/api/nltk.html#nltk.tree.Tree.productions),了解如何遍历NLTK'Tree'的示例。 –
@JonGauthier我想要做的是提取一个生产对象的双方,比如''S''和''NP VP“'。我已经阅读过'productions'方法,但是仍然不知道如何正确地遍历树。请给我看一些示例代码吗? – allenwang
'树'实例是可迭代的。 '对于t中的孩子:#孩子是树的一个实例,对应于树的孩子t' –