bộ tách câu python spacy
Sep 23 2020
Tôi muốn sử dụng spacyđể lấy các câu ra khỏi văn bản.
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)
Có thể tăng độ tin cậy của quy tắc bỏ qua bộ chia câu chẳng hạn như không bao giờ chia câu sau một từ viết tắt như "no.".
Hãy tưởng tượng tất nhiên tôi có một loạt các từ viết tắt rất kỹ thuật và cụ thể.
Bạn sẽ tiến hành như thế nào?
Trả lời
3 thorntonc Sep 23 2020 at 22:36
Bạn có thể viết một hàm tùy chỉnh thay đổi hành vi mặc định bằng cách sử dụng phương pháp tách các câu dựa trên quy tắc. Ví dụ:
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])
Điều này sẽ cung cấp cho bạn sự phân chia câu mong muốn.
Before: ['The formula is no.', '45.', 'This num.', 'represents the chemical properties.']
After: ['The formula is no. 45.', 'This num. represents the chemical properties.']