[Tutor] Reading text until a certain point

Dave Angel davea at ieee.org
Fri Jul 24 18:20:50 CEST 2009


vince spicer wrote:
> you can build a dictionary and keep the active key, again this would only
> work in predictable data
>
> users = {}
> name = None
>
> for line in file:
>     key, value = [x.strip() for x in line.split(":")]
>     if key == "name":
>         name = data[1]
>         users[name] = {} 
>      else:
>          users[name][data[0]]
>
>   
>>> users
>>>       
> {"stefan": {
>           "id":12345
>           "color":blue
> })
>
> Vince
>
> On Fri, Jul 24, 2009 at 9:39 AM, Stefan Lesicnik <stefan at lsd.co.za> wrote:
>
>   
>> Hi Guys,
>>
>> It seems like this keeps coming up (for me anyways), and i'm never sure how
>> to do it. I'm very new to programming...
>>
>> I have a file that has text in a certain format. Lets assume
>>
>> '''
>> name: stefan
>> id: 12345
>> color: blue
>> name: joe
>> id: 54321
>> color: red
>> '''
>>
>> The format is predictable.  I understand for non predictable text, you
>> would have to use pyparser or the like to build a match.
>>
>> For predictable format, I am never sure how to handle this. I normally use
>> something like
>>
>> for line in file:
>>     line.split('\n')
>>
>> The problem being i dont really do something per line?  I would like to say
>> something like, for line until the next 'name', make that 1 element.
>> So i would like to then have a list or dict (this probably makes sense for
>> a dict) with that group. I would then probably split it into various
>> elements.
>>
>> So essentially im asking, how do i say the for line until next 'match'.
>> Would this be something for the re module? Or is there an inbuilt core way?
>>
>> I hope this makes sense
>>
>> Thanks!
>>
>> Stefan
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>     
>
>   
(Don't top-post.  It makes it difficult to see the sequence of responses)

(untested)

users = {}
name = None

for line in file:
    key, value = [x.strip() for x in line.split(":")]
    if key == "name":
        name = value
        users[name] = {}
     else:
         users[name][key] = value

At this point, users is a dictionary keyed by names, and each value is a 
dictionary, keyed by 'id' and 'color'




More information about the Tutor mailing list