Newbie needs help with regex strings
Gerard Flanagan
grflanagan at yahoo.co.uk
Wed Dec 14 14:22:56 EST 2005
Fredrik Lundh wrote:
> Scott wrote:
>
> > I have a file with lines in the following format.
> >
> > pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
> > Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
> > Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'
> >
> > I would like to pull out some of the values and write them to a csv
> > file.
>
> here's a relatively straightforward re solution that gives you a dictionary
> with the values for each line.
>
> import re
>
> for line in open("infile.txt"):
> d = {}
> for k, v1, v2 in re.findall("(\w+)=(?:(\w+)|'([^']*)')", line):
> d[k.lower()] = v1 or v2
> print d
>
How about replacing
d={}
with
d = {'pie': ',', 'quantity': ',', 'cooked': ',', 'price':
',','ingredients': '', 'eol': '\n'}
to get the appropriate commas for missing fields?
Gerard
More information about the Python-list
mailing list