how to parse structured text file?

John McMonagle johnmc at velseis.com.au
Tue Jan 31 20:22:48 EST 2006


> I have a file which contains data in the format shown in the sample
> bellow.
> How can I parse it to get following:
> (14,trigger,guard,do_action,15)
> 
> Thanks a lot for your postings
> Petr Jakes
> 
> type:
> 4
> bgrColor:
> 255 255 255
> fgrColor:
> 0 0 0
> objId:
> 16
> Num.Pts:
> 2
> 177 104
> 350 134
> objStartId:
> 14
> objEndId:
> 15
> eventName:
> trigger
> eventCond:
> guard
> eventAction:
> do_action
> 
> 
> 


Create a dictionary mapping the properties to their values, then print
out the ones you require:

fid = open('xxx', 'r')
lines = fid.readlines()
fid.close()

i = 0
items = {}
for line in lines:
    line = line.strip()
    if line[-1] == ':':
        line = line.split(':')[0]
        items[line] = lines[i+1].strip()
    i = i + 1
outString = '(' +  items.get('objStartId') + ',' +
items.get('eventName') + ',' + items.get('eventCond') + ',' +
items.get('eventAction') + ',' + items.get('objEndId') + ')\n'

print outString



This code yields the following output:

(14,trigger,guard,do_action,15)

Regards,

John McMonagle



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.




More information about the Python-list mailing list