Данные, которые у меня есть, имеют довольно плохой формат .txt. Я пытаюсь уловить смысл полных слов / предложений между этими начальными и конечными строками. Прямо сейчас я обнаружил в тексте около 4 типов шаблонов подстрок. Я пытаюсь захватить строки между этими несколькими начальными и конечными подстроками. Я могу правильно записать первое появление строки, но не второе, третье и т. д.
начальная и конечная строки: FOO, БАРЫ, БАР, БАР2
text = 'I do not want this FOO string1 BARS I do not want this FOO string 2 BAR I do not want this FOO string3 BAR2 I do not want this FOO string4 BARS '
snippet1 = text[text.index('FOO')+len('FOO'):text.index('BARS')] \
if text[text.index('FOO')+len('FOO'):text.index('BARS')] else ''
snippet2 = text[text.index('FOO')+len('FOO'):text.index('BAR')] \
if text[text.index('FOO')+len('FOO'):text.index('BAR')] else ''
snippet3 = text[text.index('FOO')+len('FOO'):text.index('BAR2')] \
if text[text.index('FOO')+len('FOO'):text.index('BAR2')] else ''
# print(type(snippet1))
print('')
print('snippet1:',snippet1) #Output: snippet1: string1
print('')
print('snippet2',snippet2) # Output: snippet2 string1
print('')
print('snippet3',snippet3) # Output: snippet3 string1 BARS I do not want this FOO string2 BAR I do not want this FOO string3
# How do I get this output? Is it possible to code this?
snippet1: string1
snippet2: string2
snippet3: string3






IIUC: это можно сделать с помощью regex:
import re
txt='I do not want this FOO string1 BARS I do not want this FOO string 2 BAR I do not want this FOO string3 BAR2 I do not want this FOO string4 BARS '
re.findall('FOO(.*?)BAR', txt)
создаст список подходящих строк, например:
[' string1 ', ' string 2 ', ' string3 ', ' string4 ']
Обновление для соответствия с несколькими ключевыми словами:
import re
txt='I do not want this FOO string1 BARS I do not want this FOO string 2 SECTION I do not want this FOO string3 BAR2 I do not want this FOO string4 BARS'
re.findall('FOO(.*?)[BAR|SECTION]', txt)
приведет к:
[' string1 ', ' string 2 ', ' string3 ', ' string4 ']
Что-то вроде этого и есть то, что вам нужно.
def find_substrings(text, start_marker, end_marker):
index = 0
results = []
while True:
index = text.find(start_marker, index)
if index == -1: # If the start string wasn't found then there are no more instances left in the string
break
index2 = text.find(end_marker, index+len(start_marker))
if index2 == -1: # Sub string was not terminated.
break
results.append(text[index+len(start_marker):index2])
index = index2 + len(end_marker)
return results
В настоящее время вы используете index (который похож на find, но выдает ошибки, если он ничего не находит), но он будет каждый раз искать начало строки.
text = 'I do not want this FOO string1 BARS I do not want this FOO string 2 BAR I do not want this FOO string3 BAR2 I do not want this FOO string4 BARS '
find_substrings(text, "FOO ", " BAR")
вернусь
['string1', 'string 2', 'string3', 'string4']
Оба ответа помогли, но ответ @TobySuch хорошо вписался в мой код. Огромное спасибо!!! Я потратил слишком много времени на то, чтобы исправить это !!
Вы можете обрезать пробелы: re.findall ('FOO \ s * (. *?) \ S * BAR', текст)