Skip to content

Instantly share code, notes, and snippets.

@alixedi
Created January 8, 2016 15:42
Show Gist options
  • Save alixedi/6ffef3c7f849822201f6 to your computer and use it in GitHub Desktop.
Save alixedi/6ffef3c7f849822201f6 to your computer and use it in GitHub Desktop.
Generate templates from text.
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