regex - replace placeholder tags with dictionary fields in python -
this code far:
import re template="hello,my name [name],today [date] , weather [weather]" placeholder=re.compile('(\[([a-z]+)\])') find_tags=placeholder.findall(cam.template_id.text) fields={field_name:'michael',field_date:'21/06/2015',field_weather:'sunny'} key,placeholder in find_tags: assemble_msg=template.replace(placeholder,?????) print assemble_msg
i want replace every tag associated dictionary field , final message this: name michael,today 21/06/2015 , weather sunny. want automatically , not manually.i sure solution simple,but couldn't find far.any help?
no need manual solution using regular expressions. (in different format) supported str.format
:
>>> template = "hello, name {name}, today {date} , weather {weather}" >>> fields = {'name': 'michael', 'date': '21/06/2015', 'weather': 'sunny'} >>> template.format(**fields) hello, name michael, today 21/06/2015 , weather sunny
if can not alter template
string accordingly, can replace []
{}
in preprocessing step. note raise keyerror
in case 1 of placeholders not present in fields
dict.
in case want keep manual approach, try this:
template = "hello, name [name], today [date] , weather [weather]" fields = {'field_name': 'michael', 'field_date': '21/06/2015', 'field_weather': 'sunny'} placeholder, key in re.findall('(\[([a-z]+)\])', template): template = template.replace(placeholder, fields.get('field_' + key, placeholder))
or bit simpler, without using regular expressions:
for key in fields: placeholder = "[%s]" % key[6:] template = template.replace(placeholder, fields[key])
afterwards, template
new string replacements. if need keep template, create copy of string , replacement in copy. in version, if placeholder can not resolved, stays in string. (note swapped meaning of key
, placeholder
in loop, because imho makes more sense way.)
Comments
Post a Comment