Trying to write a python script to extract lines from a file. The file is a text file which is a dump of python suds output.
I want to:
Let's have some fun with iterators!
class SudsIterator(object):
"""extracts xsd strings from suds text file, and returns a
(key, (value1, value2, ...)) tuple with key being the 5th field"""
def __init__(self, filename):
self.data_file = open(filename)
def __enter__(self): # __enter__ and __exit__ are there to support
return self # `with SudsIterator as blah` syntax
def __exit__(self, exc_type, exc_val, exc_tb):
self.data_file.close()
def __iter__(self):
return self
def next(self): # in Python 3+ this should be __next__
"""looks for the next 'ArrayOf_xsd_string' item and returns it as a
tuple fit for stuffing into a dict"""
data = self.data_file
for line in data:
if 'ArrayOf_xsd_string' not in line:
continue
ignore = next(data)
val1 = next(data).strip()[1:-2] # discard beginning whitespace,
val2 = next(data).strip()[1:-2] # quotes, and comma
val3 = next(data).strip()[1:-2]
val4 = next(data).strip()[1:-2]
key = next(data).strip()[1:-2]
val5 = next(data).strip()[1:-2]
break
else:
self.data_file.close() # make sure file gets closed
raise StopIteration() # and keep raising StopIteration
return key, (val1, val2, val3, val4, val5)
data = dict()
for key, value in SudsIterator('data.txt'):
data[key] = value
print data