[Tutor] manipulating data

Ricardo Aráoz ricaraoz at gmail.com
Mon Nov 12 14:25:18 CET 2007


Alan Gauld wrote:
> "Bryan Fodness" <bryan.fodness at gmail.com> wrote in
> 
>> fields = {}
>> for line in open('data.txt') :
>>    if line :   ## You shouldn't need this.
>>       if line.split()[0] == 'field' :
>>           field = int(line.split()[-1])
>>       else :
>>           fields[field] = tuple(line.split())
>>
>> fields[field] = tuple(line.split())
>> NameError: name 'field' is not defined
> 
> As you should expect since you only define field inside
> the if branch so if you go down the else route first then
> field will not exist.
> 
> I'm jumping into this rather late but I'd have thought
> something like this (untested code) might work:
> 
> fields = {}
> for line in open('data.txt'):
>     try:
>        name,value = line.split()
>        fields[name] = int(value)
>     except AttributeError: pass  # catches blank lines
> 
> Or if you can control the data format the ConfigParser module
> might be a better solution.
> 
> 
> HTH,
> 

Nice use of try block!
I should point though that the OP's file has this structure :

> My data is in a file with a format, where there may be multiple fields
> > >>
> > >> field = 1
> > >>
> > >> 1a   0
> >
> >

So you have a line where you get the field key and then a line where you
get the values for that field (that's how I interpreted it), in that
case the error comes from the fact that there is no "field = n" line
before a value pair (if that would happen later the code I submitted
wouldn't catch the error). OR the OP's line "field = 0" was not part of
the file and then you have two choices, the "field" in the example
submitted is "1" and the data : (a, 0) and there may be multiple lines
with the same field, or there will be one data tuple for each "field"
value. That would be : (yes, I used Alan's code, nicer than mine)

Case 1) multiple tuples per field value
 fields = {}
 for line in open('data.txt'):
     try:
        name,value = line.split()
        fields.setdefault(name[:-1],
				[]).append(tuple(name[-1],int(value)))
     except AttributeError: pass  # catches blank lines


case 2) one tuple per field value
 fields = {}
 for line in open('data.txt'):
     try:
        name,value = line.split()
        fields[name[:-1]] = tuple(name[-1],int(value))
     except AttributeError: pass  # catches blank lines


I don't have the OP's original post at hand so maybe he should clarify
his file's structure.




More information about the Tutor mailing list