如何对NLP解析树进行反向工程以得到原始句子?

时间:2016-09-04 17:20:30

标签: regex nlp nltk stanford-nlp

给出一个解析树(使用http://nlp.stanford.edu:8080/corenlp/process漂亮的打印选项获得)

(ROOT (S (NP (PRP You)) (VP (MD could) (VP (VB say) (SBAR (IN that) (S (NP (PRP they)) (ADVP (RB regularly)) (VP (VB catch) (NP (NP (DT a) (NN shower)) (, ,) (SBAR (WHNP (WDT which)) (S (VP (VBZ adds) (PP (TO to) (NP (NP (PRP$ their) (NN exhilaration)) (CC and) (NP (FW joie) (FW de) (FW vivre))))))))))))) (. .)))

我怎么能得到原来的句子?

You could say that they regularly catch a shower, which adds to their exhilaration and joie de vivre.

我正在考虑使用一些正则表达式魔法,但我想知道斯坦福NLP是否有内置功能来执行此任务?

2 个答案:

答案 0 :(得分:3)

通常,正则表达式不足以解析树状结构。如果你想用手解析这个,最简单的方法可能是编写一个小的递归下降解析器,它将涉及编写探索每个节点的递归函数,每个叶节点的函数将附加到结果的文本。

幸运的是,我认为您不需要进行任何解析,因为Stanford NLP有几种方法可以将树转换为List个叶子,还有几种方法可以将List个叶子转换为一个Sentence。请参阅these links。具体来说,Tree的{​​{1}}方法可以派上用场。

我会尝试yield。如果这不起作用,您可以尝试Sentence.listToOriginalTextString(tree.yield())。类型签名有点尴尬,所以我不是100%自信。

答案 1 :(得分:3)

您可以使用Tree将字符串转换为Tree.fromstring()。现在,您可以使用Tree.leaves()方法从树中获取所有令牌。

代码:

from nltk import Tree

parse_str = "(ROOT (S (NP (PRP You)) (VP (MD could) (VP (VB say) (SBAR (IN that) (S (NP (PRP they)) (ADVP (RB regularly)) (VP (VB catch) (NP (NP (DT a) (NN shower)) (, ,) (SBAR (WHNP (WDT which)) (S (VP (VBZ adds) (PP (TO to) (NP (NP (PRP$ their) (NN exhilaration)) (CC and) (NP (FW joie) (FW de) (FW vivre))))))))))))) (. .)))"

t = Tree.fromstring(parse_str)

#print t.leaves()
print ' '.join(t.leaves())

<强>输出:

You could say that they regularly catch a shower , which adds to their exhilaration and joie de vivre .