In my dict, the keys are strings (which will be printed with quotes), and the
values are either strings, integers, or floats. I came up with this:
from lepl import Word, Drop, AnyBut, String, Float, Integer, Separator,
Whitespace
key = String(quote="'")
spaces = ~Whitespace()[:]
_int = Integer() >> int
_flt = Float() >> float
value = String(quote="'") | _int | _flt
with Separator (spaces):
dict_el = key & Drop(':') & value
d = Drop ('{') & dict_el[1:,Drop(',')] & Drop ('}')
Any comments? Suggestions?
Here's my code with that added:
from lepl import Word, Drop, AnyBut, String, Float, Integer, \
Separator, Whitespace
key = String(quote="'")
spaces = ~Whitespace()[:]
_int = Integer() >> int
_flt = Float() >> float
value = String(quote="'") | _int | _flt
with Separator (spaces):
dict_el = key & Drop(':') & value > tuple
d = Drop ('{') & dict_el[1:,Drop(',')] & Drop ('}') > dict
print d.parse_string("{'a': 1, 'b': 2.3, 'c': 'd'}")[0]
Which prints:
{u'a': 1, u'c': u'd', u'b': 2.3}
In case it's not obvious the reason this works is that the tuple creates
(key, value) pairs and the standard dict constructor will actually accept a
list of pairs and construct a dict.
Andrew
On Fri, 15 Oct 2010 14:20:19 -0400, Neal Becker <ndbe...@gmail.com>
wrote:
> --
> You received this message because you are subscribed to the Google Groups "lepl" group.
> To post to this group, send email to le...@googlegroups.com.
> To unsubscribe from this group, send email to lepl+uns...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/lepl?hl=en.
>
>
It would be slightly neater and easier to understand, but by default it
doesn't match newlines (while Whitespace does) so you'd need:
with DroppedSpace(Whitespace()[:]):
(I was thinking people would want to handle newlines themselves, but I am
not sure that is the most common case in retrospect).
Andrew