如何在Python中使用Stanford Parser的Typed Dependencies?

时间:2014-07-01 02:02:15

标签: python stanford-nlp

要查看Typed Dependencies的示例,请查看this online example输出的结尾。

当我使用lexparser.sh在命令行上运行stanford解析器时,它会输出树和类型化的依赖项。

但是当我使用nltk.parse.stanford运行它时,我得到的只是树,没有类型依赖。我可以通过设置-outputFormat =" penn,typedDependencies"来修改它以返回依赖项。 as documented here,虽然我只是得到了文字。我想知道其他人是否已经完成了将其处理成更有用的形式的工作。

斯坦福CoreNLP网站lists several extensions for Python,尽管其中大多数似乎都是相关的分叉。 From glancing at the source code, this one looks promising for dealing with dependencies,虽然它完全没有记录,但我不确定如何使用它。

许多这些库提供了作为服务运行并通过HTTP进行通信的功能。我想知道这是否会比NLTK与解析器交互的方式更快,因为它可能不需要新的JVM重复启动。

我不太确定CoreNLP和Stanford Parser之间的区别是什么。

我还发现了this,虽然它使用的是JPype但我无法编译它。

2 个答案:

答案 0 :(得分:1)

我最近做了一个严重依赖CoreNLP和Stanford Parser的项目。首先,如果您要使用它,我强烈建议您使用Java编写代码,因为在Python中使用它是一件巨大的痛苦。但是,我确实设法让它发挥作用。

我建议使用this与CoreNLP对话,它对我来说效果最好。这将需要声明JVM并在本地与它通信(尽管它会为您执行此操作)。它还有可爱的错误,有时要么返回上一个解析而不是刚刚发送的解析,要么根本不返回。我们使用了一个装饰器,它会在一段时间后重新启动解析,可以找到here

祝你好运,因为这是一项艰巨的任务。另请注意,与完整CoreNLP相比,NTLK Stanford解析器不完整。您不应该使用NTLK来使用CoreNLP,它将提供从NER到POS到依赖项所需的一切。

答案 1 :(得分:0)

刚刚给出了另一个更适合这个问题的答案:)

我使用minidom解析了CoreNLP的输出。以下是您可能想要使用的一些入门代码,但您可能需要查看https://github.com/dasmith/stanford-corenlp-python

请注意,您需要获取Stanford CoreNLP使用的标记化,因为返回的数据基于句子和标记的偏移量。

from xml.dom import minidom    
xmldoc = minidom.parseString(raw_xml_data)
for sentence_xml in xmldoc.getElementsByTagName('sentences')[0].getElementsByTagName('sentence'):
    parse = parser.parse(sentence_xml.getElementsByTagName('parse')[0].firstChild.nodeValue)
    tokens = [(i,j) for i,j in zip(sentence_xml.getElementsByTagName('tokens')[0].getElementsByTagName('token'),parse.get_leaves())]
    # example for processing dependencies
    elements = sentence_xml.getElementsByTagName('dependencies')
    for element in elements:
        if element.getAttribute('type')=="collapsed-ccprocessed-dependencies":
            dependencies += [i for i in element.getElementsByTagName('dep')]