首页 > 解决方案 > 使用 spacy sentenizer 拆分句子

问题描述

我正在使用 spaCy 的语句器来拆分句子。

from spacy.lang.en import English
nlp = English()
sbd = nlp.create_pipe('sentencizer')
nlp.add_pipe(sbd)

text="Please read the analysis. (You'll be amazed.)"
doc = nlp(text)

sents_list = []
for sent in doc.sents:
   sents_list.append(sent.text)

print(sents_list)
print([token.text for token in doc])

输出

['Please read the analysis. (', 
"You'll be amazed.)"]

['Please', 'read', 'the', 'analysis', '.', '(', 'You', "'ll", 'be', 
'amazed', '.', ')']

标记化已正确完成,但我不确定它不会将第二句与 ( 并将其作为第一句的结尾。

标签: python-3.xnlpspacy

解决方案


我用 en_core_web_lg 和 en_core_web_sm 模型测试了下面的代码,sm 模型的性能类似于使用 sentencizer。(lg模型会影响性能)。

自定义边界以下仅适用于 sm 模型,并且与 lg 模型进行不同的拆分。

nlp=spacy.load('en_core_web_sm')
def set_custom_boundaries(doc):
    for token in doc[:-1]:
        if token.text == ".(" or token.text == ").":
            doc[token.i+1].is_sent_start = True
        elif token.text == "Rs." or token.text == ")":
            doc[token.i+1].is_sent_start = False
    return doc

nlp.add_pipe(set_custom_boundaries, before="parser")
doc = nlp(text)

for sent in doc.sents:
 print(sent.text)

推荐阅读