Parsing complex text file in Python -
i have text file following:
#some_line @another_line original_string1|new_string1 #some_other_line @and_another_line original_string2|new_string2
i want able associate every line @ preceding line #. cannot seem figure out strategy achieve in python.
here current code:
open(self.file, 'r') f: 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 able reference each parent entry , associate child entries it. lines '|' need associated parent well.
i think want mapping child strings parent strings. or maybe want mapping child strings , parent strings line numbers.
so here's i'll do: build mappings strings line numbers (i'm assuming each 1 unique, should easy fix if not), , build mapping child line numbers parent line numbers. if needed string-to-string mapping, or else, should able figure out this.
the strings-to-line-numbers part trivial, child-to-parent part, need keep track of last parent line number we've seen.
child_lines, parent_lines, child_parents = {}. {}. {} last_parent_line = none open(self.file) f: i, line in enumerate(f): line = line.strip(' \t\n\r') marker, value = line[0], line[1:] if marker == '#': parent_lines[value] = last_parent_line = elif marker == '@': child_lines[value] = child_parents[i] = last_parent_line
that's it.
Comments
Post a Comment