python-stanford-corenlp:基于 Stanford CoreNLP 的 Python 接口项目

Python interface to CoreNLP using a bidirectional server-client interface.

分支1Tags0
文件最后提交记录最后更新时间
4 年前
7 年前
9 年前
7 年前
9 年前
9 年前
9 年前
9 年前
9 年前
5 年前
9 年前
7 年前
8 年前

斯坦福 CoreNLP Python 接口

注意: 该包已弃用。请使用 stanza 包代替。

.. image:: https://travis-ci.org/stanfordnlp/python-stanford-corenlp.svg?branch=master :target: https://travis-ci.org/stanfordnlp/python-stanford-corenlp

该包包含了一个用于 Stanford CoreNLP 的 Python 接口,它提供了一个与 Stanford CoreNLP 服务器 交互的参考实现。该包还包含一个基类,以便通过轻量级服务将基于 Python 的注释提供者(例如您喜欢的神经 NER 系统)暴露给 CoreNLP 管道。

要使用该包,首先下载 官方 Java CoreNLP 发行版,解压,并定义一个环境变量 :code:$CORENLP_HOME 指向解压后的目录。

您也可以通过 PyPI 使用 :code:pip install stanford-corenlp 命令安装此包。


命令行使用

使用此包的最简单方法是通过 annotate 命令行工具:

用法:annotate [-h] [-i INPUT] [-o OUTPUT] [-f {json}] [-a ANNOTATORS [ANNOTATORS ...]] [-s] [-v] [-m MEMORY] [-p PROPS [PROPS ...]]

注释数据

可选参数:
  -h, --help            显示此帮助消息并退出
  -i INPUT, --input INPUT
                        要处理的输入文件;每行包含一个文档(默认:标准输入)
  -o OUTPUT, --output OUTPUT
                        将注释写入的文件(默认:标准输出)
  -f {json}, --format {json}
                        输出格式
  -a ANNOTATORS [ANNOTATORS ...], --annotators ANNOTATORS [ANNOTATORS ...]
                        注解器列表
  -s, --sentence-mode   假设输入的每一行都是一个句子。
  -v, --verbose-server  服务器变为详细模式
  -m MEMORY, --memory MEMORY
                        服务器使用的内存
  -p PROPS [PROPS ...], --props PROPS [PROPS ...]
                        作为键值对列表的属性

我们建议将 annotate 与出色的 jq 命令一起使用来处理输出。例如,给定一个每行有一个句子的文件,以下命令产生一个等价的空格分隔的标记:

cat file.txt | annotate -s -a tokenize | jq '[.tokens[].originalText]' > tokenized.txt

注释服务器使用

.. code-block:: python

import corenlp

text = "Chris wrote a simple sentence that he parsed with Stanford CoreNLP."

我们假设您已下载 Stanford CoreNLP 并定义了一个环境变量 $CORENLP_HOME

指向解压后的目录。以下代码将在后台启动 StanfordCoreNLPServer

并与服务器通信以注释句子。

with corenlp.CoreNLPClient(annotators="tokenize ssplit pos lemma ner depparse".split()) as client: ann = client.annotate(text)

您可以使用 ann 访问注释。

sentence = ann.sentence[0]

corenlp.to_text 函数是一个辅助函数,它

从令牌重建句子。

assert corenlp.to_text(sentence) == text

您可以访问句子中的任何属性。

print(sentence.text)

同样适用于令牌

token = sentence.token[0] print(token.lemma)

使用 tokensregex 模式查找谁写了句子。

pattern = '([ner: PERSON]+) /wrote/ /an?/ []{0,3} /sentence|article/' matches = client.tokensregex(text, pattern)

sentences 包含每个句子的匹配列表。

assert len(matches["sentences"]) == 1

length 告诉您此处是否有任何匹配

assert matches["sentences"][0]["length"] == 1

您可以像大多数正则表达式组一样访问匹配项。

matches["sentences"][1]["0"]["text"] == "Chris wrote a simple sentence" matches["sentences"][1]["0"]["1"]["text"] == "Chris"

使用 semgrex 模式直接查找谁写了什么。

pattern = '{word:wrote} >nsubj {}=subject >dobj {}=object' matches = client.semgrex(text, pattern)

sentences 包含每个句子的匹配列表。

assert len(matches["sentences"]) == 1

length 告诉您此处是否有任何匹配

assert matches["sentences"][0]["length"] == 1

您可以像大多数正则表达式组一样访问匹配项。

matches["sentences"][1]["0"]["text"] == "wrote" matches["sentences"][1]["0"]["subject"]["text"]=="Chris"matches["sentences"][1]["0"]["subject"]["text"] == "Chris" matches["sentences"][1]["0"]["object"]["text"] == "sentence"

更多信息请查看 test_client.pytest_protobuf.py。感谢 @dan-zheng 对 tokensregex/semgrex 的支持。

注释服务使用

注意: 注释服务允许用户提供一个自定义注释器供 CoreNLP 管道使用。不幸的是,它依赖于斯坦福 CoreNLP 项目内部的实验性代码,目前不可供公众使用。

.. code-block:: python

import corenlp from .happyfuntokenizer import Tokenizer

class HappyFunTokenizer(Tokenizer, corenlp.Annotator): def init(self, preserve_case=False): Tokenizer.init(self, preserve_case) corenlp.Annotator.init(self)

@property
def name(self):
    """
    注释器名称(由 CoreNLP 使用)
    """
    return "happyfun"

@property
def requires(self):
    """
    Requires 必须指定在我们被调用之前需要的所有注释。
    """
    return []

@property
def provides(self):
    """
    在我们完成时保证提供的注释集。
    注意:这些注释要么是完全限定的 Java 类名,要么是指向
    edu.stanford.nlp.ling.CoreAnnotations 的嵌套类(如下所示)。
    """
    return ["TextAnnotation",
            "TokensAnnotation",
            "TokenBeginAnnotation",
            "TokenEndAnnotation",
            "CharacterOffsetBeginAnnotation",
            "CharacterOffsetEndAnnotation",
           ]

def annotate(self, ann):
    """
    @ann: 是一个 protobuf 注释对象。
    实际上用令牌填充 @ann。
    """
    buf, beg_idx, end_idx = ann.text.lower(), 0, 0
    for i, word in enumerate(self.tokenize(ann.text)):
        token = ann.sentencelessToken.add()
        # 这些是 TokenAnnotation 所需的最低要求
        token.word = word
        token.tokenBeginIndex = i
        token.tokenEndIndex = i+1

        # 寻找文本,直到可以找到这个单词。
        try:
            # 尝试更新起始索引
            beg_idx = buf.index(word, beg_idx)
        except ValueError:
            # 放弃——这将是一些随机的东西
            end_idx = beg_idx + len(word)

        token.beginChar = beg_idx
        token.endChar = end_idx

        beg_idx, end_idx = end_idx, end_idx

annotator = HappyFunTokenizer()

调用 .start() 将启动注释器作为在默认端口 8432 上运行的服务。

annotator.start()

annotator.properties 包含所有正确的属性,供 Stanford CoreNLP 使用此注释器。

with corenlp.CoreNLPClient(properties=annotator.properties, annotators="happyfun ssplit pos".split()) as client: ann = client.annotate("RT @ #happyfuncoding: this is a typical Twitter tweet 😃")

tokens = [t.word for t in ann.sentence[0].token]
print(tokens)

更多信息请查看 test_annotator.py

项目介绍

Python interface to CoreNLP using a bidirectional server-client interface.

定制我的领域