将文本分成句子 NLTK 与 spaCy

Ber*_*nes 4 python nlp nltk sentence spacy

我想将文本分成句子。

查看堆栈溢出我发现:

与NLTK

from nltk.tokenize import sent_tokenize
text="""Hello Mr. Smith, how are you doing today? The weathe is great, and city is awesome. The sky is pinkish-blue. You shouldn't eat cardboard"""
tokenized_text=sent_tokenize(text)
print(tokenized_text)
Run Code Online (Sandbox Code Playgroud)

与斯帕西

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 在后台必须用所谓的 create_pipe 做不同的事情。句子对于训练您自己的 NLP 词嵌入非常重要。spaCy 不直接包含开箱即用的句子标记器应该是有原因的。

谢谢。

注意:请注意,简单的 .split(.) 不起作用,文本中有几个十进制数字以及包含“.”的其他类型的标记。

ong*_*enz 6

默认情况下,spaCy 使用其依赖解析器进行句子切分,这需要加载统计模型。这sentencizer是一个基于规则的句子分段器,您可以使用它来定义自己的句子分段规则,而无需加载模型。

如果您不介意保持解析器处于激活状态,可以使用以下代码:

import spacy
nlp = spacy.load('en_core_web_sm') # or whatever model you have installed
raw_text = 'Hello, world. Here are two sentences.'
doc = nlp(raw_text)
sentences = [sent.text.strip() for sent in doc.sents]
Run Code Online (Sandbox Code Playgroud)