Elegant way to extract values from a string parsed with a template
I have a template like this:
foo_tmplte = Template("fieldname_${ln}_${type} = $value")
and a lot of strings parsed with this template like thi开发者_JAVA技巧s:
foo_str1 = "fieldname_ru_ln = journal"
foo_str2 = "fieldname_zh_TW_ln = journal"
foo_str3 = "fieldname_uk_ln = номер запису"
Now i want to extract back the variables from the template, for example with str1 the result must be:
ln = ru
type = ln
value = journal
I try some approaches but I can't find any elegant and reusable function to extract the variables. Any idea?
Thanks in advance
Why don't you use regexps? They have named groups and you can extract them in a dictionary.
Tue Aug 17 14:33:58 $ python
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> foo_template = re.compile(r"^fieldname_(?P<ln>\w+?)_(?P<type>\w+) = (?P<value>.*)$")
>>> m = foo_template.match("fieldname_zh_TW_ln = journal")
>>> m
<_sre.SRE_Match object at 0x7ff34840>
>>> m.groupdict()
{'ln': 'zh', 'type': 'TW_ln', 'value': 'journal'}
>>>
You could use Jinja2, a general-purpose templating library. You'd have to change the string format, though:
"fieldname_{{ ln }}"
精彩评论