views:

47

answers:

2

Hello all,

I have a template like this:

foo_tmplte = Template("fieldname_${ln}_${type} = $value")

and a lot of strings parsed with this template like this:

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

A: 

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'}
>>> 
cadrian
Thanks for your answer cadrian the problem is the templates are generated by the user and the strings are made using the templates. so this code is valid in this case but not in this(for example):foo_tmplte = Template("fieldfoo_${type} = $value")who generates this strings:foo_str1 = "fieldfoo_ln = journal"foo_str2 = "fieldfoo_ln = journal"foo_str3 = "fieldfoo_ln = номер запису"
fsouto
OK, in that case you could use a regexp to transform the $... sections into proper regexp groups ;-) Do the curly brackets have any special meaning?
cadrian
A: 

You could use Jinja2, a general-purpose templating library. You'd have to change the string format, though:

"fieldname_{{ ln }}"
loevborg