我正在寻找用于将输出格式化为简单文本的 Python 技术或模板系统。我需要的是它将能够迭代多个列表或字典。如果我能够将模板定义到单独的文件(如output.templ)中而不是将其硬编码到源代码中,那就太好了。
作为我想要实现的简单示例,我们有变量title
, subtitle
and list
title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
通过模板运行,输出将如下所示:
Foo
Bar
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
这个怎么做?谢谢。
您可以使用标准库string http://docs.python.org/library/string.html#template-strings其模板类。
有文件foo.txt
:
$title
$subtitle
$list
以及文件的处理(example.py
):
from string import Template
d = {
'title': 'This is the title',
'subtitle': 'And this is the subtitle',
'list': '\n'.join(['first', 'second', 'third'])
}
with open('foo.txt', 'r') as f:
src = Template(f.read())
result = src.substitute(d)
print(result)
然后运行它:
$ python example.py
This is the title
And this is the subtitle
first
second
third
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)