[Tutor] parsing a "chunked" text file

Andrew Fithian afith13 at gmail.com
Tue Mar 2 07:22:43 CET 2010


Hi tutor,

I have a large text file that has chunks of data like this:

headerA n1
line 1
line 2
...
line n1
headerB n2
line 1
line 2
...
line n2

Where each chunk is a header and the lines that follow it (up to the next
header). A header has the number of lines in the chunk as its second field.

I would like to turn this file into a dictionary like:
dict = {'headerA':[line 1, line 2, ... , line n1], 'headerB':[line1, line 2,
... , line n2]}

Is there a way to do this with a dictionary comprehension or do I have to
iterate over the file with a "while 1" loop?

-Drew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100301/9ef380c4/attachment.html>


More information about the Tutor mailing list