将文本分为句子NLTK vs spaCy

时间:2019-06-02 15:55:36

标签: python nlp nltk spacy sentence

我想将文本分成句子。

我在堆栈溢出中发现:

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)

有空间

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]

问题是,在后台使用spacy必须使用所谓的create_pipe进行不同处理。 句子对于训练自己的NLP单词嵌入非常重要。 spaCy不直接在框外包括句子标记器是有原因的。

谢谢。

注意:请注意,简单的.split(。)无效,文本中有多个十进制数字,而其他类型的标记中也包含'。'

2 个答案:

答案 0 :(得分:1)

默认情况下,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.string.strip() for sent in doc.sents]

答案 1 :(得分:0)

spaCy中的处理管道具有模块化设置,此处提供更多信息:https://spacy.io/usage/processing-pipelines。您可以通过定义管道来定义所需的零件。在某些用例中,您可能不需要句子,例如,当您只想用词袋表示时。因此,我想这可能就是为什么sentencizer并不总是自动包含的原因-但如果需要的话,它就在那里。

请注意,English()是一个非常通用的模型-您可以在此处找到一些更有用的预训练统计模型:https://spacy.io/models/en