Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace placeholder tags with dictionary fields in python

Tags:

python

regex

this is my code so far:

import re
template="Hello,my name is [name],today is [date] and the weather is [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'}

for key,placeholder in find_tags:
assemble_msg=template.replace(placeholder,?????)
print assemble_msg

I want to replace every tag with the associated dictionary field and the final message to be like this: My name is Michael,today is 21/06/2015 and the weather is sunny. I want to do this automatically and not manually.I am sure that the solution is simple,but I couldn't find any so far.Any help?

like image 746
pankar Avatar asked Jun 04 '15 14:06

pankar


2 Answers

No need for a manual solution using regular expressions. This is (in a slightly different format) already supported by str.format:

>>> template = "Hello, my name is {name}, today is {date} and the weather is {weather}"
>>> fields = {'name': 'Michael', 'date': '21/06/2015', 'weather': 'sunny'}
>>> template.format(**fields)
Hello, my name is Michael, today is 21/06/2015 and the weather is sunny

If you can not alter your template string accordingly, you can easily replace the [] with {} in a preprocessing step. But note that this will raise a KeyError in case one of the placeholders is not present in the fields dict.


In case you want to keep your manual approach, you could try like this:

template = "Hello, my name is [name], today is [date] and the weather is [weather]"
fields = {'field_name': 'Michael', 'field_date': '21/06/2015', 'field_weather': 'sunny'}
for placeholder, key in re.findall('(\[([a-z]+)\])', template):
    template = template.replace(placeholder, fields.get('field_' + key, placeholder))

Or a bit simpler, without using regular expressions:

for key in fields:
    placeholder = "[%s]" % key[6:]
    template = template.replace(placeholder, fields[key])

Afterwards, template is the new string with replacements. If you need to keep the template, just create a copy of that string and do the replacement in that copy. In this version, if a placeholder can not be resolved, it stays in the string. (Note that I swapped the meaning of key and placeholder in the loop, because IMHO it makes more sense that way.)

like image 75
tobias_k Avatar answered Sep 22 '22 03:09

tobias_k


You can use dictionaries to put data straight into strings, like so...

fields={'field_name':'Michael','field_date':'21/06/2015','field_weather':'sunny'}
string="Hello,my name is %(field_name)s,today is %(field_date)s and the weather is %(field_weather)s" % fields

This might be an easier alternative for you?

like image 33
Songy Avatar answered Sep 19 '22 03:09

Songy