Извлечение 25 слов с обеих сторон слова из текста - PullRequest
0 голосов
/ 09 февраля 2019

У меня есть следующий текст, и я пытаюсь использовать этот шаблон, чтобы извлечь 25 слов для каждой стороны совпадений.Проблема состоит в том, что совпадения перекрываются, поэтому механизм регулярных выражений python берет только одно совпадение.Я был бы признателен, если бы кто-нибудь мог помочь исправить это

Текст

Перспективы на 2015 год Компания предоставляет следующий прогноз на 2015 год вместо официальных финансовых рекомендаций на данный момент.Этот прогноз не учитывает влияние любых будущих приобретений и операционных расходов.Выручка. Исходя из выручки за четвертый квартал 2014 года, добавления новых товаров на нашем объекте и ранее открытого приобретения «Важного места», Компания ожидает, что использование текущих 100 предметов будет оставаться в среднем на уровне

* 1006.* Я попробовал следующий шаблон
pattern = r'(?<=outlook\s)((\w+.*?){25})'

Это создает одно совпадение, тогда как мне нужно два совпадения, и не должно иметь значения, перекрывает ли одно другое

Мне нужно в основном два совпадения

Ответы [ 2 ]

0 голосов
/ 09 февраля 2019

Я бы вообще не использовал регулярное выражение - питон module re не обрабатывает перекрывающиеся диапазоны ...

text = """2015 Outlook The Company is providing the following outlook for 2015 in lieu of formal financial guidance at this time. This outlook does not include the impact of any future acquisitions and transaction-related costs. Revenues - Based on the revenues from the fourth quarter of 2014, the addition of new items at our some facility and the previously opened acquisition of Important Place, the Company expects utilization of the current 100 items to remain in some average"""

lookfor = "outlook"

# split text at spaces
splitted = text.lower().split()

# get the position in splitted where the words match (remove .,-?! for comparison) 
positions = [i for i,w in enumerate(splitted) if lookfor == w.strip(".,-?!")]


# printing here, you can put those slices in a list for later usage
for p in positions:    # positions is: [1, 8, 21]
    print( ' '.join(splitted[max(0,p-26):p+26]) )
    print()

Вывод:

2015 outlook the company is providing the following outlook for 2015 in lieu of formal financial guidance at this time. this outlook does not include the impact

2015 outlook the company is providing the following outlook for 2015 in lieu of formal financial guidance at this time. this outlook does not include the impact of any future acquisitions and transaction-related costs.

2015 outlook the company is providing the following outlook for 2015 in lieu of formal financial guidance at this time. this outlook does not include the impact of any future acquisitions and transaction-related costs. revenues - based on the revenues from the fourth quarter of 2014, the

Итерируя разделенные слова, выполучить позиции и нарезать разделенный список.Обязательно начинайте с 0 для среза, даже если p-26 ниже, чем 0, иначе вы не получите никакого вывода.(Начало -4 означает конец строки)

0 голосов
/ 09 февраля 2019

A без регулярных выражений путь:

string = "2015 Outlook The Company is providing the following outlook for 2015 in lieu of formal financial guidance at this time. This outlook does not include the impact of any future acquisitions and transaction-related costs. Revenues - Based on the revenues from the fourth quarter of 2014, the addition of new items at our some facility and the previously opened acquisition of Important Place, the Company expects utilization of the current 100 items to remain in some average"
words = string.split()
starting25 = " ".join(words[:25])
ending25 = " ".join(words[-25:])
print(starting25)
print("\n")
print(ending25)
...