Monday, 12 August 2013

Parsing complex text file in Python

Parsing complex text file in Python

I have a text file like the following:
#some_line
@another_line
original_string1|new_string1
#some_other_line
@and_another_line
original_string2|new_string2
I want to be able to associate every line with an @ to the preceding line
with a #. I cannot seem to figure out a strategy to achieve this in
python.
Here is my current code:
with open(self.file, 'r') as f:
for i, line in enumerate(f):
line = line.strip(' \t\n\r')
if '#' in line[:1]:
self.parent[i] = line[1:]
if '@' in line[:1]:
self.child[i] = line[1:]
if '|' in line:
key, value = line.split('|')
self.strings[key] = value
I need to be able to reference each parent entry and associate the child
entries with it. The lines with a '|' also need to be associated with the
parent as well.

No comments:

Post a Comment