У меня возникли проблемы с правильным определением предложений в тексте для конкретных угловых случаев:
- Если используется точка, точка, точка, это не будет сохранено.
- Если задействовано
"
.
- Если предложение случайно начинается со строчной буквы.
Так я до сих пор идентифицировал предложения в тексте (источник: Переформатирование субтитров, чтобы завершить полное предложение ):
re.findall
part в основном ищет фрагмент str
, который начинается с заглавной буквы [A-Z]
, затем что-нибудь, кроме знаков препинания, а затем заканчивается пунктуацией, [\.?!]
.
import re
text = "We were able to respond to the first research question. Next, we also determined the size of the population."
for sentence in re.findall(r'([A-Z][^\.!?]*[\.!?])', text):
print(sentence + "\n")
We were able to respond to the first research question.
Next, we also determined the size of the population.
Угловой корпус 1: Точка, Точка, Точка
Точка, точка, точка не сохраняется, поскольку не дано никаких инструкций о том, что делать, если в строке появляются три точки. Как это можно изменить?
text = "We were able to respond to the first research question... Next, we also determined the size of the population."
for sentence in re.findall(r'([A-Z][^\.!?]*[\.!?])', text):
print(sentence + "\n")
We were able to respond to the first research question.
Next, we also determined the size of the population.
Угловой корпус 2: "
Символ "
успешно удерживается в предложении, но, как и точка после пунктуации, он будет удален в конце.
text = "We were able to respond to the first \"research\" question: \"What is this?\" Next, we also determined the size of the population."
for sentence in re.findall(r'([A-Z][^\.!?]*[\.!?])', text):
print(sentence + "\n")
We were able to respond to the first "research" question: "What is this?
Next, we also determined the size of the population.
Угловой регистр 3: начало предложения в нижнем регистре
Если предложение случайно начинается со строчной буквы, предложение будет проигнорировано. Цель состоит в том, чтобы определить, что предыдущее предложение закончилось (или текст только что начался), и, следовательно, новое предложение должно начинаться.
text = "We were able to respond to the first research question. next, we also determined the size of the population."
for sentence in re.findall(r'([A-Z][^\.!?]*[\.!?])', text):
print(sentence + "\n")
We were able to respond to the first research question.
Большое спасибо за любую помощь!
Edit:
Я проверял это:
import spacy
from spacy.lang.en import English
raw_text = 'Hello, world. Here are two sentences.'
nlp = English()
doc = nlp(raw_text)
sentences = [sent.string.strip() for sent in doc.sents]
... но я получаю:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-157-4fd093d3402b> in <module>()
6 nlp = English()
7 doc = nlp(raw_text)
----> 8 sentences = [sent.string.strip() for sent in doc.sents]
<ipython-input-157-4fd093d3402b> in <listcomp>(.0)
6 nlp = English()
7 doc = nlp(raw_text)
----> 8 sentences = [sent.string.strip() for sent in doc.sents]
doc.pyx in sents()
ValueError: [E030] Sentence boundaries unset. You can add the 'sentencizer' component to the pipeline with:
nlp.add_pipe (nlp.create_pipe ('круглое предложение)) В качестве альтернативы, добавьте
анализатор зависимостей или установите границы предложений, установив
документ [я] .is_sent_start.