如何使用python nltk获取解析树?

2024-06-14 13:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下句子:

The old oak tree from India fell down.

如何使用python NLTK获得句子的以下解析树表示?

(ROOT (S (NP (NP (DT The) (JJ old) (NN oak) (NN tree)) (PP (IN from) (NP (NNP India)))) (VP (VBD fell) (PRT (RP down)))))

我需要一个完整的例子,我在网上找不到!


编辑

我通过this book chapter学习使用NLTK进行语法分析,但问题是,我需要语法来分析我没有的句子或短语。我发现this stackoverflow post也问过语法分析,但没有令人信服的答案。

所以,我正在寻找一个完整的答案,可以给我一个句子的解析树。


Tags: the答案fromtreenprootnnthis
2条回答

旧问题,但是可以将nltk与bllipparser一起使用。这是一张longer example from nltk。我自己摆弄了几下之后,就用了下面的:

要安装(已安装nltk):

sudo python3 -m nltk.downloader bllip_wsj_no_aux
pip3 install bllipparser

使用:

from nltk.data import find
from bllipparser import RerankingParser

model_dir = find('models/bllip_wsj_no_aux').path
parser = RerankingParser.from_unified_model_dir(model_dir)

best = parser.parse("The old oak tree from India fell down.")

print(best.get_reranker_best())
print(best.get_parser_best())

输出:

-80.435259246021 -23.831876011253 (S1 (S (NP (NP (DT The) (JJ old) (NN oak) (NN tree)) (PP (IN from) (NP (NNP India)))) (VP (VBD fell) (PRT (RP down))) (. .)))
-79.703612178593 -24.505514522222 (S1 (S (NP (NP (DT The) (JJ old) (NN oak) (NN tree)) (PP (IN from) (NP (NNP India)))) (VP (VBD fell) (ADVP (RB down))) (. .)))

这里是使用StanfordCoreNLP而不是nltk的替代解决方案。很少有库建立在StanfordCoreNLP之上,我个人使用pycorenlp来解析这个句子。

首先,您必须下载^{}文件夹,其中包含*.jar文件。并在文件夹中运行服务器(默认端口为9000)。

export CLASSPATH="`find . -name '*.jar'`"
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer [port?] # run server

然后在Python中,可以运行以下命令来标记句子。

from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')

text = "The old oak tree from India fell down."

output = nlp.annotate(text, properties={
  'annotators': 'parse',
  'outputFormat': 'json'
})

print(output['sentences'][0]['parse']) # tagged output sentence

相关问题 更多 >