Newbie needs help with regex strings

Michael Spencer mahs at telcopartners.com
Wed Dec 14 15:18:19 EST 2005


Catalina Scott A Contr AFCA/EVEO 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.
> 
> For line in filea
> 	pie = regex
> 	quantity = regex
> 	cooked = regex
> 	ingredients = regex
> 	fileb.write (quantity,pie,cooked,ingredients)
> 
> How can I retreive the values and assign them to a name?
> 
> Thank you
> Scott

Here's a trick to parse this source, exploiting the fact that its syntax mimics 
python's keyword arguments.  All that's needed is a way to quote the bare names:

  >>> class lazynames(dict):
  ...     def __getitem__(self, key):
  ...         if key in self:
  ...             return dict.__getitem__(self, key)
  ...         return "%s" % key # if name not found, return it as a str constant
  ...
  >>> d = lazynames(dict=dict, __builtins__ = None)


  >>> source = """\
  ... 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'
  ... """
  >>>
  >>> [eval("dict(%s)" % line, d) for line in source.splitlines()]
  [{'cooked': 'yes', 'ingredients': 'sugar and cinnamon', 'pie': 'apple', 
'quantity': 1}, {'ingredients': 'peaches,powdered sugar', 'Pie': 'peach', 
'quantity': 2}, {'cooked': 'no', 'price': 5, 'ingredients': 'cherries and 
sugar', 'Pie': 'cherry', 'quantity': 3}]
  >>>

Michael




More information about the Python-list mailing list