У меня длинные текстовые строки и я хочу прочитать текст между двумя словами. Это большой текстовый файл в стандартном формате:
First Paragraph
(Empty line)
Random lines are in this file with different words. Some
random lines are in this file with some different words. Some words here
random lines are in this file with various different words. Many words
random lines are in this file with plenty of different words
(Empty line)
Second Paragraph
(Empty line)
Я ищу текст между первым и вторым абзацами. Я попробовал несколько подходов, используя spacy, но не смог получить то, что я хочу.
#Approach 1: This approach doesn't return anything
import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
pattern = [{'LOWER': 'first'}, {'LOWER': 'second'}]
matcher.add("FindParagrpah", None, pattern)
doc = nlp(random_text_from_file_in_String_format)
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id] # Get string representation
span = doc[start:end] # The matched span
print(match_id, string_id, start, end, span.text)
#Approach 2: This returns the whole text instead of expected text between First and Second words.
import spacy
nlp = spacy.load("en_core_web_sm")
def custom_boundary(docx):
for token in docx[:-1]:
if token.text == 'Second':
docx[token.i+1].is_sent_start=True
return docx
nlp.add_pipe(custom_boundary,before='parser')
mysentence= nlp(text)
for sentence in mysentence.sents:
print(sentence)
Что я делаю не так? Должен ли я использовать какую-то другую библиотеку? Любая помощь будет оценена. Спасибо.