parsing string to a list of objects - help!
Paul McGuire
ptmcg at austin.rr.com
Mon Nov 5 04:26:25 EST 2007
On Nov 5, 3:00 am, Donn Ingle <donn.in... at gmail.com> wrote:
>
> I have glanced around at parsing and all the tech-speak confuses the heck
> out of me. I am not too smart and would appreciate any help that steers
> away from cold theory and simply hits at this problem.
>
Donn -
Here is a pyparsing version that I hope is fairly easy-to-read and
tech-speak free:
from pyparsing import *
frame = Literal("#")
tween = Word("-") # that is, it is a "word" composed of 1 or more -'s
copy = Literal("=")
blank = Literal("_")
animation = OneOrMore((frame + Optional(
(tween + FollowedBy(frame)) |
OneOrMore(copy | blank) ) ) )
test = "#---#--#===_#"
print animation.parseString(test)
This prints the following:
['#', '---', '#', '--', '#', '=', '=', '=', '_', '#']
>From here, the next step would be to define classes that these matched
tokens could be converted to. Pyparsing allows you to attach a method
to individual expressions using setParseAction - if you pass a class
instead of a method, then class instances are returned. For these
tokens, you could write:
class Prop(object):
def __init__(self,tokens):
pass
class Tween(object):
def __init__(self,tokens):
self.tween = tokens[0]
self.tweenLength = len(self.tween)
class CopyPrevious(object):
def __init__(self,tokens):
pass
class Blank(object):
def __init__(self,tokens):
pass
frame.setParseAction(Prop)
tween.setParseAction(Tween)
copy.setParseAction(CopyPrevious)
blank.setParseAction(Blank)
And now calling animation.parseString(test) returns a sequence of
objects representing the input string's frames, tweens, etc.:
[<__main__.Prop object at 0x00B9D8F0>, <__main__.Tween object at
0x00BA5390>, <__main__.Prop object at 0x00B9D9B0>, <__main__.Tween
object at 0x00BA55F0>, <__main__.Prop object at 0x00BA5230>,
<__main__.CopyPrevious object at 0x00BA58F0>, <__main__.CopyPrevious
object at 0x00BA59D0>, <__main__.CopyPrevious object at 0x00BA5AB0>,
<__main__.Blank object at 0x00BA5B70>, <__main__.Prop object at
0x00BA5510>]
Now you can implement behavior in these 4 classes to implement the
tweening, copying, etc. behavior that you want, and then walk through
this sequence invoking this animation logic.
-- Paul
More information about the Python-list
mailing list