ตัวแยกประโยค python spacy

Sep 23 2020

ฉันต้องการใช้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)

เป็นไปได้หรือไม่ที่จะเพิ่มความน่าเชื่อถือของกฎการข้ามตัวแยกประโยคเนื่องจากไม่เคยแบ่งประโยคหลังตัวย่อเช่น "ไม่"

ลองนึกภาพว่าฉันมีคำย่อทางเทคนิคและคำย่อที่เฉพาะเจาะจงมากมาย
คุณจะดำเนินการอย่างไร?

คำตอบ

3 thorntonc Sep 23 2020 at 22:36

คุณสามารถเขียนฟังก์ชันแบบกำหนดเองที่เปลี่ยนพฤติกรรมเริ่มต้นโดยใช้วิธีการแยกประโยคตามกฎ ตัวอย่างเช่น:

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

สิ่งนี้จะทำให้คุณแยกประโยคที่ต้องการ

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