quickly read a formated file?

Jussi Salmela tiedon_jano at hotmail.com
Thu Mar 1 09:09:31 EST 2007


rzed kirjoitti:
> bearophileHUGS at lycos.com wrote in
> news:1172740062.523000.209320 at 8g2000cwh.googlegroups.com: 
> 
>> lialie:
>>> The formated file may be very popularly, but the module
>>> ConfigPaser doesn't handle it. Is there a way to process it
>>> freely? 
>> First try, assuming the input file can be read whole. The code
>> isn't much readable, it needs better variable names (name
>> names?), comments, etc.
>>
>> data = """
>> %HEADER
>> title1 = "Untilted1"
>> username = "User1"
>>
>> %DATA
>> title2 = "Untilted2"
>> username2 = "User2"
>> """
>>
>> l1 = (p.strip().splitlines() for p in data.split("%") if
>> p.strip()) result = {}
>> for part in l1:
>>     pairs1 = (pair.split('=') for pair in part[1:])
>>     pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in 
> pairs1) result[part[0]] = dict(pairs2)
>> print result
>>
>>
> 
> If there could be embedded perecent signs in the data, that will 
> produce some unexpected results, though. Here's another shot:
> 
> 
> <snip>
> 
> 

The solution of bearophile only needs 2 small modifications to handle this:

#=========================================
data = """
%HEADER
title1 = "Untilted1"
username = "User1 20 %"

%DATA
title2 = "Untilted2"
username2 = "User2 10 %"
"""

# Ensure data starts with a newline
data = '\n' + data

# Split using '\n%' instead of '%'
l1 = (p.strip().splitlines() for p in data.split("\n%") if p.strip())
result = {}
for part in l1:
     pairs1 = (pair.split('=') for pair in part[1:])
     pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in pairs1)
     result[part[0]] = dict(pairs2)
print result
#=========================================



Cheers,
Jussi



More information about the Python-list mailing list