如何使用Spacy按句子分解文档

Ula*_*ach 6 python spacy

如何将文档(例如段落,书籍等)分解为句子。

例如,"The dog ran. The cat jumped"["The dog ran", "The cat jumped"] 与spacy?

小智 17

在 spacy 3.0.1 中,他们改变了管道。

from spacy.lang.en import English 

nlp = English()
nlp.add_pipe('sentencizer')


def split_in_sentences(text):
    doc = nlp(text)
    return [str(sent).strip() for sent in doc.sents]
Run Code Online (Sandbox Code Playgroud)

  • 从 spacy 3.0 开始,这应该是公认的答案 (4认同)

KB_*_*KB_ 12

回答

import spacy
nlp = spacy.load('en_core_web_sm')

text = 'My first birthday was great. My 2. was even better.'
sentences = [i for i in nlp(text).sents]
Run Code Online (Sandbox Code Playgroud)

附加信息
这假设您已经在您的系统上安装了模型“en_core_web_sm”。如果没有,您可以通过在终端中运行以下命令轻松安装它:

$ python -m spacy download en_core_web_sm
Run Code Online (Sandbox Code Playgroud)

(有关所有可用模型的概述,请参见此处。)

根据您的数据,这可以带来比仅使用spacy.lang.en.English. 一个(非常简单的)比较示例:

import spacy
from spacy.lang.en import English

nlp_simple = English()
nlp_simple.add_pipe(nlp_simple.create_pipe('sentencizer'))

nlp_better = spacy.load('en_core_web_sm')


text = 'My first birthday was great. My 2. was even better.'

for nlp in [nlp_simple, nlp_better]:
    for i in nlp(text).sents:
        print(i)
    print('-' * 20)
Run Code Online (Sandbox Code Playgroud)

输出:

>>> My first birthday was great.
>>> My 2.
>>> was even better.
>>> --------------------
>>> My first birthday was great.
>>> My 2. was even better.
>>> --------------------
Run Code Online (Sandbox Code Playgroud)


npi*_*pit 10

最新的答案是这样的:

from __future__ import unicode_literals, print_function
from spacy.lang.en import English # updated

raw_text = 'Hello, world. Here are two sentences.'
nlp = English()
nlp.add_pipe(nlp.create_pipe('sentencizer')) # updated
doc = nlp(raw_text)
sentences = [sent.string.strip() for sent in doc.sents]
Run Code Online (Sandbox Code Playgroud)

  • spacy 3.0.6:将`sent.string.strip()`更改为`sent.text.strip()` (5认同)
  • 实际上,在 spacy 3.0 中,语法现在是 `nlp.add_pipe('sentencizer')` 正如 @user8189050 所说。 (3认同)
  • 这使用基于规则的方法,而不是统计模型来分割句子。对于我的用例,使用“en_core_web_sm”效果更好,“en_core_web_lg”效果更好,并且速度足以满足我的需求。请参阅[KB_的回答](/sf/answers/4287790251/)。 (2认同)

Ula*_*ach 9

spacy的github支持页面

from __future__ import unicode_literals, print_function
from spacy.en import English

raw_text = 'Hello, world. Here are two sentences.'
nlp = English()
doc = nlp(raw_text)
sentences = [sent.string.strip() for sent in doc.sents]
Run Code Online (Sandbox Code Playgroud)

  • 该答案自 2019 年起已过时(SpaCy 2.1.8)。npit@ 答案更好。 (3认同)