Extract specific lines from file and create sections of data in python

后端 未结 3 2090
再見小時候
再見小時候 2021-01-21 15:31

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:

  1. strip all charac
3条回答
  •  囚心锁ツ
    2021-01-21 15:44

    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
    

提交回复
热议问题