Skip to content

Instantly share code, notes, and snippets.

@kergoth
Created April 25, 2010 01:32
Show Gist options
  • Save kergoth/378086 to your computer and use it in GitHub Desktop.
Save kergoth/378086 to your computer and use it in GitHub Desktop.
from pyparsing import *
from string import printable
data = "${foo} ${${bar}} whee ${ bar ${baz ${meh} moo}}"
datastore = {
"foo": "fooval",
"bar": "barval",
"barval": "barvalval",
"meh": "MEH",
"baz MEH moo": "heh.",
" bar heh.": "dance!",
}
expanded_data = "fooval barvalval whee dance!"
def getVar(tokens):
var = tokens[0]
val = "".join(var.asList())
if val in datastore:
tokens[0] = datastore[val]
content = Combine(OneOrMore(~Literal("${") + ~Literal("}") +
Word(printable, exact=1)))
content.leaveWhitespace()
var = nestedExpr("${", "}", ignoreExpr=None, content=content)
var.setParseAction(getVar)
newdata = var.transformString(data)
assert(newdata == expanded_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment