John Lam 1997 — 2026

Python and parsing

Wow. I’m having fun tonight. I discovered a package called ToyParser which is an LL parser generator with limited backtracking abilities. It’s sufficient for building simple grammars for little languages.

I refactored my earlier program that parses song input, and I defined a little language for scripting Microsoft Agent characters. Here’s a simple script that I just wrote:

show
move 300,400
play Greet
speak "Hello, Matthew!"
speak "I'm so happy to meet you!!"
play Pleased
speak "I hear it's your birthday!"
speak "So I will sing you a birthday song!"
play MoveRight
move 1000,0
sing "!f#c Hap- #c p #d birth-#c day !s#f to #e you."
sing "!f#c Hap- #c p #d birth-#c day !s#g to #f you."
sing "!f#c Hap- #c p #cc birth- #aa day !s#f to  #e Maa- #d foo."
sing "!f#bbf Hap- #bbf p #aa birth- #f day !s#g to #f you."
play Wave
speak "Would you like to play a game?"
play DoMagic1
speak "Isn't this great magic?"
hide

And here is the ridiculously simple Python program that I wrote that parses it. Notable things in this program are my first Python classes, SongParser and AgentParser. Also, notice how I use the exec statement to execute the code that my AgentParser class generates:

import re
import tpg
import win32com.client
import fileinput

class SongParser:
    notes = dict([['c',65],['d',73],['e',82],['f',87],\
                  ['g',98],['aa',110],['bbf',117],['cc',131]])
    tempo = dict([['f',130],['s',55]])

    re_markup = re.compile(r'([\#|\!])(\w+)', re.IGNORECASE)

    markup = dict([['#', (lambda mo : '\\pit=%s\\' \
                          % SongParser.notes[mo.group(2)])],
                   ['!', (lambda mo : '\\spd=%s\\' \
                          % SongParser.tempo[mo.group(2)])]])

    def parseSong(self, song):
        return '\\chr=\"monotone\"\\' + \
               SongParser.re_markup.sub(lambda mo : \
                                        SongParser.markup[mo.group(1)](mo), song)

class AgentParser(tpg.Parser):
    r"""
        # Tokens
        separator   spaces  '\s+';
        token       int     '\d+' int;
        token       id      '\w+' ;
        token       string  '\".*\"' ;

        # Rules
        START/s -> statement/s (statement/k $ s += k $)*;
        statement/s -> (show/k | move/k | play/k | speak/k | sing/k | hide/k) $ s = 'self.agent.%s\n' % k $;

        show/s  -> 'show'                               $ s = 'Show()' $;
        move/m  -> 'move' int/x ',' int/y               $ m = "MoveTo(%i, %i)" % (x, y) $;
        play/p  -> 'play' id/n                          $ p = "Play(\"%s\")" % n $;
        speak/s -> 'speak' string/n                     $ s = "Speak(%s)" % n $;
        sing/s  -> 'sing' string/n                      $ s = "Speak(self.songParser.parseSong(%s))" % n$;
        hide/h  -> 'hide'                               $ h = 'Hide()' $;
    """
    def __init__(self, name, file, size):
        self.server = win32com.client.Dispatch("Agent.Control.2")
        self.songParser = SongParser()
        self.server.Connected = -1
        self.server.Characters.Load(name, file)
        self.agent = self.server.Characters(name)
        self.agent.Width = size;
        self.agent.Height = size;
        tpg.Parser.__init__(self)

    def run(self, expr):
        exec self(expr)

peedy = AgentParser("Peedy", "Peedy.acs", 600)
for line in fileinput.input():
    peedy.run(line)
fileinput.close()

I’m blown away by how productive this environment is.

3 archived reader comments

Sy (2004-09-19)

This looks really interesting, especially the sing command :). I’m absolutely new to Python and was trying to run your script in Pythonwin but I don’t know where the value of expr comes in. It will be cool if you can post source files and compile instructions… Its a nice brithday app anyhow :)

John Lam (2004-09-19)

Sy, you’ll need to save my test script as a separate file, and pass the path to that filename as a command-line argument to the python script. When you run the script under PythonWin, it will prompt you for command-line arguments when you run your app.

Enjoy!

John Lam (2004-09-20)

Hey Gordon: you’ll need to download the Lernout and Hauspie text to speect engine from: http://www.microsoft.com/msagent/downloads/user.asp.