Читайте строки между начальным и конечным словами в Python 3, используя обработку на основе правил - PullRequest
0 голосов
/ 13 марта 2020

У меня длинные текстовые строки и я хочу прочитать текст между двумя словами. Это большой текстовый файл в стандартном формате:

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)

Что я делаю не так? Должен ли я использовать какую-то другую библиотеку? Любая помощь будет оценена. Спасибо.

1 Ответ

0 голосов
/ 14 марта 2020

Если в текстовых данных есть пустая строка; возможно, вы можете использовать некоторое регулярное выражение:

import re

DATA = """First Paragraph

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

Second Paragraph
"""

paragraph = re.split(r"\n\n", DATA)
print(paragraph[1])

параграф будет списком, и он будет содержать 3 элемента;

, если вы напечатаете второй элемент, который является абзацем [1], вывод будет :

Случайные строки в этом файле с разными словами. В этом файле есть несколько случайных строк с разными словами. Некоторые слова здесь случайные строки в этом файле с различными словами. Много слов случайных строк в этом файле с множеством разных слов

...