我正在寻找Python的技术或模板系统,以便将输出格式化为简单文本.我需要的是它能够遍历多个列表或dicts.如果我能够将模板定义到单独的文件(如output.templ)而不是将其硬编码到源代码中,那将是很好的.
作为我想要实现的简单示例,我们有变量title,subtitle和list
title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
并运行模板,输出将如下所示:
Foo
Bar
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
这该怎么做?谢谢.
Thi*_*hib 181
您可以使用标准库字符串模板:
所以,你有一个文件foo.txt与
$title
...
$subtitle
...
$list
和一本字典
d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }
然后它很简单
from string import Template
#open the file
filein = open( 'foo.txt' )
#read it
src = Template( filein.read() )
#do the substitution
src.substitute(d)
然后你可以打印 src
当然,正如Jammon所说,你有很多其他好的模板引擎(这取决于你想做什么......标准的字符串模板可能是最简单的)
foo.txt的
$title
...
$subtitle
...
$list
example.py
from string import Template
#open the file
filein = open( 'foo.txt' )
#read it
src = Template( filein.read() )
#document data
title = "This is the title"
subtitle = "And this is the subtitle"
list = ['first', 'second', 'third']
d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }
#do the substitution
result = src.substitute(d)
print result
然后运行example.py
$ python example.py
This is the title
...
And this is the subtitle
...
first
second
third
Obe*_*nne 14
如果您更喜欢使用标准库附带的东西,请查看格式字符串语法.默认情况下,它无法像输出示例中那样格式化列表,但您可以使用自定义格式化程序来处理此方法,该格式化程序会覆盖该convert_field方法.
假设您的自定义格式化程序cf使用转换代码l格式化列表,这应该产生您给定的示例输出:
cf.format("{title}\n{subtitle}\n\n{list!l}", title=title, subtitle=sibtitle, list=list)
或者,您可以使用预格式化列表"\n".join(list),然后将其传递给普通模板字符串.