python spacy句子分割器

Ber*_*nes 2 python sentence spacy

我想用它spacy从文本中取出句子。

nlp = English()  # just the language with no model
sentencizer = nlp.create_pipe("sentencizer")
nlp.add_pipe(sentencizer)
doc = nlp("This is a sentence. This is another sentence.")
for sent in doc.sents:
    print(sent.text)
Run Code Online (Sandbox Code Playgroud)

是否有可能提高句子分割器绕过规则的可靠性,例如从不在像“no.”这样的首字母缩略词之后分割句子。

当然,想象一下我有一堆非常技术性和特殊的缩写词。
你将如何进行?

tho*_*onc 5

您可以编写一个自定义函数,通过使用基于规则的句子拆分方法来更改默认行为。例如:

import spacy

text = "The formula is no. 45. This num. represents the chemical properties."

nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
print("Before:", [sent.text for sent in doc.sents])

def set_custom_boundaries(doc):
    pattern_a = ['no', 'num']
    for token in doc[:-1]:
        if token.text in pattern_a and doc[token.i + 1].text == '.':
            doc[token.i + 2].is_sent_start = False
    return doc

nlp.add_pipe(set_custom_boundaries, before="parser")
doc = nlp(text)
print("After:", [sent.text for sent in doc.sents])
Run Code Online (Sandbox Code Playgroud)

这将为您提供所需的句子拆分。

Before: ['The formula is no.', '45.', 'This num.', 'represents the chemical properties.']
After: ['The formula is no. 45.', 'This num. represents the chemical properties.']
Run Code Online (Sandbox Code Playgroud)