extracting string.Template substitution placeholders

Discussion in 'Python' started by Eric S. Johansson, Jan 12, 2014.

  1. As part of speech recognition accessibility tools that I'm building, I'm
    using string.Template. In order to construct on-the-fly grammar, I need
    to know all of the identifiers before the template is filled in. what is
    the best way to do this?

    can string.Template handle recursive expansion i.e. an identifier
    contains a template.

    Thanks
    --- eric
     
    Eric S. Johansson, Jan 12, 2014
    #1
    1. Advertisements


  2. py> import string
    py> t = string.Template("$sub some $text $here")
    py> t.template
    '$sub some $text $here'

    Now just walk the template for $ signs. Watch out for $$ which escapes
    the dollar sign. Here's a baby parser:

    def get_next(text, start=0):
    while True:
    i = text.find("$", start)
    if i == -1:
    return
    if text[i:i+2] == '$$':
    start += i
    continue
    j = text.find(' ', i)
    if j == -1:
    j = len(text)
    assert i < j
    return (text[i:j], j)

    start = 0
    while start < len(t.template):
    word, start = get_next(t.template, start)
    print(word)

    If you mean, recursive expand the template until there's nothing left to
    substitute, then no, not directly. You would have to manually expand the
    template yourself.
     
    Steven D'Aprano, Jan 13, 2014
    #2
    1. Advertisements

  3. found a different way

    import string
    cmplxstr="""a simple $string a longer $string a $last line"""
    nst=string.Template(cmplxstr)

    identifiers = {}

    while True:
    try:
    result = nst.substitute(identifiers)
    except KeyError, error:
    print error
    identifiers[error[0]] = "x"
    else:
    break
    print "loop done"
     
    Eric S. Johansson, Jan 15, 2014
    #3
  4. Eric S. Johansson

    gmflanagan Guest

    Try this:

    import string
    cmplxstr="""a simple $string a longer $string a $last line ${another} one"""

    def finditer(s):
    for match in string.Template.pattern.finditer(s):
    arg = match.group('braced') or match.group('named')
    if arg:
    yield arg


    if __name__ == '__main__':
    print set(finditer(cmplxstr))
     
    gmflanagan, Jan 17, 2014
    #4
  5. Would you please read and action this
    https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the
    double line spacing above, thanks.
     
    Mark Lawrence, Jan 17, 2014
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.