Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python re.findall from file

Tags:

python

I am trying to extract all of the text between two keywords in a text file. The keywords appear multiple times in the file, so I will have multiple blocks of good text.

The input.txt file is this:

bad bad keyword1 GOOD DATA keyword2 bad
bad bad bad keyword1 MORE 
GOOD DATA keyword2 bad bad 

This is not working:

import re

f = open('input.txt', 'r')
trim = re.findall('keyword1(.+?)keyword2', f.read())
print trim

It returns an empty list:

[]
like image 597
Linda Shaw Avatar asked Aug 01 '26 04:08

Linda Shaw


2 Answers

If you want to grab all the data you should use re.DOTALL flag:

trim = re.findall('keyword1(.+?)keyword2', f.read(), re.DOTALL)

Usually the dot character means to get all chars but \n. With the DOTALL attribute the engine also matches \n for the dot character.

Output:

[' GOOD DATA ', ' MORE \nGOOD DATA ']
like image 65
Rodrigo López Avatar answered Aug 03 '26 16:08

Rodrigo López


import re

s = "bad bad keyword1 GOOD DATA " \
    "keyword2 bad bad bad bad " \
    "keyword1 MORE GOOD DATA " \
    "keyword2 bad bad"

for i in re.findall('keyword1(.*?)keyword2', s, re.DOTALL):
    print(i)
like image 45
nullptr Avatar answered Aug 03 '26 17:08

nullptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!