到目前为止这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
我想用相关的字典字段替换每个标签,最后的消息是这样的:我的名字是迈克尔,今天是2015年6月21日,天气晴朗.我想自动而不是手动执行此操作.我确信解决方案很简单,但到目前为止我找不到任何帮助.有什么帮助吗?
无需使用正则表达式的手动解决方案.这是(略有不同的格式)已经支持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
Run Code Online (Sandbox Code Playgroud)
如果你不能改变你的template相应的字符串,可以方便地更换[]与{}在预处理步骤.但请注意,KeyError如果其中一个占位符不在fieldsdict中,则会引发此问题.
如果您想保留手动方法,可以尝试这样:
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))
Run Code Online (Sandbox Code Playgroud)
或者更简单,不使用正则表达式:
for key in fields:
placeholder = "[%s]" % key[6:]
template = template.replace(placeholder, fields[key])
Run Code Online (Sandbox Code Playgroud)
之后,template是带有替换的新字符串.如果您需要保留模板,只需创建该字符串的副本并在该副本中进行替换.在此版本中,如果无法解析占位符,则它将保留在字符串中.(注意我在循环中交换了key和的意思placeholder,因为恕我直言,这样做更有意义.)
| 归档时间: |
|
| 查看次数: |
2315 次 |
| 最近记录: |