Created
January 8, 2016 15:42
-
-
Save alixedi/6ffef3c7f849822201f6 to your computer and use it in GitHub Desktop.
Generate templates from text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def xtemplate(toks, str): | |
''' | |
A function that generates templates from given tokens and | |
strings. We are using this to generate email templates: | |
>>> sep = [(',', ','), ('-', '-'), ('_', '_')] | |
>>> ini = [('$fini', 'a'), ('$lini', 'z')] | |
>>> name = [('$fname', 'ali'), ('$lname', 'zaidi')] | |
>>> toks = sep + ini + name | |
>>> xtemplate(toks, 'ali.zaidi') | |
'$fname.$lname' | |
>>> xtemplate(toks, 'ali-zaidi') | |
'$fname-$lname' | |
>>> xtemplate(toks, 'ali-') | |
'$fname-' | |
>>> xtemplate(toks, 'zaidi') | |
'$lname' | |
>>> xtemplate(toks, 'a.zaidi') | |
'$fini.$lname' | |
>>> xtemplate(toks, 'a.z') | |
'$fini.$lini' | |
>>> xtemplate(toks, 'az') | |
'$fini$lini' | |
>>> xtemplate(toks, 'cake') | |
'c$finike' | |
''' | |
if toks == [] or str == '': | |
return str | |
toks = toks[:] | |
key, val = toks.pop() | |
residue = [xtemplate(toks, r) for r in str.split(val)] | |
return key.join(residue) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment