JFerro
JFerro

Reputation: 3433

python spacy sentence splitter

I would like to use spacy to get the sentences out of a text.

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)

Is it possible to increase the reliability of the sentence splitter bypassing rules as for instance never divides a sentence after an acronym like "no.".

Imagine of course I have a bunch of very technical and particular acronyms.
How would you proceed?

Upvotes: 2

Views: 2254

Answers (1)

thorntonc
thorntonc

Reputation: 2126

You can write a custom function that changes the default behavior by using a rule-based approach of splitting on sentences. For example:

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])

This will give you the desired sentence split.

Before: ['The formula is no.', '45.', 'This num.', 'represents the chemical properties.']
After: ['The formula is no. 45.', 'This num. represents the chemical properties.']

Upvotes: 5

Related Questions