Python技术或简单的模板系统用于纯文本输出

2024-06-03 02:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找Python的技术或模板系统,以便将输出格式化为简单文本。我需要的是它能够遍历多个列表或指令。如果我能将模板定义为单独的文件(如output.temp),而不是硬编码为源代码,那就太好了。

作为我想要实现的简单示例,我们有变量titlesubtitlelist

title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

通过一个模板,输出如下:

Foo
Bar

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

怎么做?谢谢您。


Tags: 文本模板列表title系统技术listsubtitle
3条回答

如果您喜欢使用标准库附带的内容,请查看format string syntax。默认情况下,它不能像输出示例中那样格式化列表,但可以使用重写^{}方法的custom Formatter来处理此问题。

假设您的自定义格式化程序cf使用转换代码l格式化列表,这将生成给定的示例输出:

cf.format("{title}\n{subtitle}\n\n{list!l}", title=title, subtitle=sibtitle, list=list)

或者,可以使用"\n".join(list)预处理列表,然后将其传递给普通模板字符串。

python有很多模板引擎:JinjaCheetahGenshietc。你不会对他们中的任何一个犯错误。

您可以使用标准库string template

所以你有一个文件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

示例.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

相关问题 更多 >