Extract data from ASCII file

Anton Vredegoor anton at vredegoor.doge.nl
Tue Feb 24 10:10:02 EST 2004


"Mike C. Fletcher" <mcfletch at rogers.com> wrote:

>Oh, and since someone took issue with my use of (new in Python 2.2) 
>yield (luddites :) ;) ), here's a non-generator version using the same 
>basic code pattern:
>
> >>> def splitter( line ):
>...     line = line[9:] # skip prefix
>...     result = []
>...     while line:
>...         prefix, line = line[:4],line[4:]
>...         result.append( prefix[2:]+prefix[:2] )
>...     return result

The basic problem with this code pattern is that it makes a lot of
large slices of the line. With a small line there is no problem but it
looks like it doesn't scale well.

After reconsidering all alternatives I finally favor a variant of
Irmen's code, but without slicing the whole line and -after all-
definitely *using* yield because it seems appropriate here.

    def process(line,offset):
        for i in xrange(offset,len(line),4):
            yield line[i+2:i+4] + line[i:i+2]
    
    def test():
        line = ":10000000E7280530AC00A530AD00AD0B0528AC0BE2"
        print '\n'.join(process(line,9))
    
    if __name__=='__main__':
        test()

output is:

28E7
3005
00AC
30A5
00AD
0BAD
2805
0BAC
E2

Anton



More information about the Python-list mailing list