A simple Example of Parsing with Esrapy

esrapy is yparse backwards

This was just a quick email response to someone who wasn't familiar with parsing and grammars and whatnot and so had no idea what Esrapy was good for. The example on the main esrapy page is for parsing a tiny computer language, so this example is for parsing a tiny human language:

So, for instance, you could provide a grammar (Pattern) like this:

	SPACE = <[ \t]*>
	noun   = "dog" | "cat" | "boy"
	proper = "Suzie" | "Simon"
	verb   = "ate" | "walked" | "confused"

	nounphrase = "the" noun | proper
	phrase = nounphrase verb nounphrase

And then (I'm going to actually plug that into esrapy, so this will
be a real example), I can feed it input and it will parse them into
parse trees like this:

	"the dog ate Suzie" ->
	[['the', 'dog'], 'ate', 'Suzie']

Though that's not very impressive since it's leaving too much
implicit, so esrapy let's you label things like:

	SPACE = <[ \t]*>
	noun   = "dog" | "cat" | "boy"
	proper = "Suzie" | "Simon"
	verb   = "ate" | "walked" | "confused"

	nounphrase = regular; "the" _:noun | proper; proper
	phrase = subject:nounphrase verb:verb object:nounphrase

And now it does this:

	"the dog ate Suzie" ->
	{'verb': 'ate', 'object': ('proper', 'Suzie'),
		'subject': ('regular', 'dog')}

	"Simon confused Suzie" ->
	{'object': ('proper', 'Suzie'),
	 'subject': ('proper', 'Simon'),
	 'verb': 'confused'}

	"Simon ate the dog" ->
	{'verb': 'ate', 'object': ('regular', 'dog'),
	 'subject': ('proper', 'Simon')}

	"the boy walked the cat" ->
	{'verb': 'walked', 'object': ('regular', 'cat'),
	 'subject': ('regular', 'boy')}

Hey, it works!  Neat.  (I haven't tried applying it to natural
language yet, and this is a trivial example but still it's neat it
just worked as expected without a hitch.)

For reference, the python commands to actually do the above would be:

import esrapy

pat = esrapy.compile("""
SPACE = <[ \t]*>
noun   = "dog" | "cat" | "boy"
proper = "Suzie" | "Simon"
verb   = "ate" | "walked" | "confused"

nounphrase = regular; "the" _:noun | proper; proper
phrase = subject:nounphrase verb:verb object:nounphrase
""")

print '"the boy walked the cat" ->'
print pat.match("the boy walked the cat")

-Simon (simonfunk@gmail.com) March 25, 2006