I am an amateur using Python on and off for some time now. Sorry if this is a silly question, but I was wondering if anyone knew an easy way to grab a bunch of lines if the
You could use a variable to mark where which heading you are currently tracking, and if it is set, grab every line until you find another heading:
data = {}
for line in file:
line = line.strip()
if not line: continue
if line.startswith('Heading '):
if line not in data: data[line] = []
heading = line
continue
data[heading].append(line)
Here's a http://codepad.org snippet that shows how it works: http://codepad.org/KA8zGS9E
Edit: If you don't care about the actual heading values and just want a list at the end, you can use this:
data = []
for line in file:
line = line.strip()
if not line: continue
if line.startswith('Heading '):
continue
data.append(line)
Basically, you don't really need to track a variable for the heading, instead you can just filter out all lines that match the Heading pattern.
Generator Functions
def group_by_heading( some_source ):
buffer= []
for line in some_source:
if line.startswith( "Heading" ):
if buffer: yield buffer
buffer= [ line ]
else:
buffer.append( line )
yield buffer
with open( "some_file", "r" ) as source:
for heading_and_lines in group_by_heading( source ):
heading= heading_and_lines[0]
lines= heading_and_lines[1:]
# process away.
Other than a generator, I think we can create a dict where the key is "Heading" and the value is one list to save the lines. Here is the code
odd_map = {}
odd_list = []
with open(file, 'r') as myFile:
lines = myFile.readlines()
for line in lines:
if "Heading" in line:
odd_list = []
odd_map[line.strip()] = odd_list
else:
odd_list.append(line.strip())
for company, odds in odd_map.items():
print(company)
for odd in odds:
print(odd)
I don't really know Python, but here's a bit of pseudocode.
int header_found=0;
[start where loop where you're looping through lines of file]
if(header_found==1) [grab line]; header_found=0;
if(line=~/[regexp for header]/) header_found=1;
The idea is to have a variable that keeps track of whether or not you've found a header, and if you have, to grab the next line.