我们可以使用 NLTK 的斯坦福解析器。
要求
您需要从他们的网站下载两个东西:
- The 斯坦福 CoreNLP 解析器 https://nlp.stanford.edu/software/lex-parser.shtml#Download.
-
语言模型 http://nlp.stanford.edu/software/corenlp.shtml为您想要的语言(例如英语语言模型 http://nlp.stanford.edu/software/stanford-english-corenlp-2018-02-27-models.jar)
Warning!
确保您的语言模型版本与斯坦福 CoreNLP 解析器版本相匹配!
截至 2018 年 5 月 22 日,当前 CoreNLP 版本为 3.9.1。
下载这两个文件后,将 zip 文件解压到您喜欢的任何位置。
Python代码
接下来,加载模型并通过NLTK使用
from nltk.parse.stanford import StanfordDependencyParser
path_to_jar = 'path_to/stanford-parser-full-2014-08-27/stanford-parser.jar'
path_to_models_jar = 'path_to/stanford-parser-full-2014-08-27/stanford-parser-3.4.1-models.jar'
dependency_parser = StanfordDependencyParser(path_to_jar=path_to_jar, path_to_models_jar=path_to_models_jar)
result = dependency_parser.raw_parse('I shot an elephant in my sleep')
dep = result.next()
list(dep.triples())
Output
最后一行的输出是:
[((u'shot', u'VBD'), u'nsubj', (u'I', u'PRP')),
((u'shot', u'VBD'), u'dobj', (u'elephant', u'NN')),
((u'elephant', u'NN'), u'det', (u'an', u'DT')),
((u'shot', u'VBD'), u'prep', (u'in', u'IN')),
((u'in', u'IN'), u'pobj', (u'sleep', u'NN')),
((u'sleep', u'NN'), u'poss', (u'my', u'PRP$'))]
我想这就是你想要的。