pembagi kalimat spacy python

Sep 23 2020

Saya ingin menggunakan spacyuntuk mengeluarkan kalimat dari teks.

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)

Apakah mungkin untuk meningkatkan keandalan aturan melewati pemisah kalimat karena misalnya tidak pernah membagi kalimat setelah akronim seperti "tidak.".

Bayangkan tentu saja saya memiliki banyak akronim yang sangat teknis dan khusus.
Bagaimana Anda akan melanjutkan?

Jawaban

3 thorntonc Sep 23 2020 at 22:36

Anda dapat menulis fungsi kustom yang mengubah perilaku default dengan menggunakan pendekatan berbasis aturan untuk memisahkan kalimat. Sebagai contoh:

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

Ini akan memberi Anda pemisahan kalimat yang diinginkan.

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