在Python中,使用字典字段替换占位符标签

7
这是我的目前的代码:

这是我的目前的代码:

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

我想用相关的字典字段替换每个标签,并使最终消息如下: 我的名字是Michael,今天是2015年6月21日,天气晴朗。 我想自动化这个过程,而不是手动操作。我相信解决方案很简单,但到目前为止我还没有找到任何方法。有什么帮助吗?

1
尝试运行这段代码,看看它是否适用于你的问题:'我的名字是{name}'.format(name='Ian') - kylieCatt
2个回答

11

不需要使用正则表达式手动解决此问题。这已经被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

如果您无法相应地更改template字符串,您可以在预处理步骤中轻松地用{}替换[]。但请注意,如果fields字典中不存在占位符之一,则会引发KeyError异常。
如果您想保持手动方式,您可以尝试以下方法:
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))

或者更简单一些,不使用正则表达式:

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

之后,template 是新的字符串替换后得到的结果。如果您需要保留模板,请创建该字符串的副本并在副本中进行替换。在此版本中,如果无法解析占位符,则占位符将保留在字符串中。(请注意,在循环中我交换了 keyplaceholder 的含义,因为我认为那样更有意义。)


2
这是格式化此类内容的正确方式。如果OP需要保留模板:new_var = template.format(**fields),则模板的值将保持不变。 - kylieCatt
实际上,@tobias_k,最终的消息是不正确的。如果你在每个循环中打印消息,你会发现它每次都替换相关的标签,但当它修复第二个标签时,第一个标签是[name]。当它去改变第三个标签时,其他的是[name]和[date]。 - pankar
1
@pankar 你可能正在使用 new_string = template.replace(...) 的方式。这样做会每次都使用原始模板。应该使用 template = template.replace(...) 或者 new_string = template,然后再使用 new_string = new_string.replace(...) - tobias_k

2
您可以使用字典将数据直接放入字符串中,如下所示...
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

这可能是一个更容易的选择?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接