extract to dictionaries

Gary Herron gherron at islandtraining.com
Fri May 29 17:22:12 CEST 2009


Marius Retegan wrote:
> Hi,
>
> On Fri, May 29, 2009 at 2:09 AM, Gary Herron 
> <gherron at islandtraining.com <mailto:gherron at islandtraining.com>> wrote:
>
>     Marius Retegan wrote:
>
>         Hello
>         I have simple text file that I have to parse. It looks
>         something like
>         this:
>
>         parameters1
>             key1 value1
>             key2 value2
>         end
>
>         parameters2
>             key1 value1
>             key2 value2
>         end
>
>         So I want to create two dictionaries parameters1={key1:value1,
>         key2:value2} and the same for parameters2.
>
>         I would appreciate any help that could help me solve this.
>         Thank you
>          
>
>
>     This looks like a homework problem. 
>
>
> It's not. I'm passed homework age.
>  
>
>       But even if it's not, you are not likely to find someone who is
>     willing to put more work into this problem than you have.
>     So  why don't you show us what you've tried, and see if someone is
>     willing to make suggestions or answer specific question about your
>     attempt at a solution?
>
>
> I don't now if posting a code that gets into a while loop and never 
> stops would demonstrate to you that I've tried. Be assured that before 
> posting to the list I did try to solve it myself, because I knew that 
> I might get an answer like RTFM or similar.
> Maybe I'm not smart enough, but I can't make python to start reading 
> after the "parameter1" line and stop at the "end" line. That's all I 
> want a small piece of pseudocode to do just that.

OK.  Assuming you are open a file with something like:
f = open('data', 'r')

Then this will read lines up to the first "parameters" line
for line in f:
    if line.startswith('parameters'):
       break

At this point, line contains 'parameters1\n'.  Do with it as you will.

Then read and process lines until an end line is reached
for line in f:
    if line.beginswith('end'):
        break
    # Here line contains  '    key1 value1\n'.
    # Perhaps use line.strip to remove the white space on each end
    # and k,v =line.split() to split out the two values on the line.

You'll need more:
  A loop to keep the above two going until the end of file
  A way to recognize the end of the file.

Gary Herron

>
> Thanks
>  
>
>
>     Gary Herron
>
>




More information about the Python-list mailing list