Python中是否有原生的纯文本文件模板系统?
我在找一种技术或者模板系统,用于Python编程,目的是把输出格式化成简单的文本。我需要的功能是能够遍历多个列表或者字典。如果能把模板定义在一个单独的文件里(比如叫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
该怎么做呢?谢谢。
4 个回答
20
如果你想用标准库里自带的东西,可以看看格式字符串的语法。默认情况下,它不能像你给出的例子那样格式化列表,但你可以通过一个自定义格式化器来解决这个问题,这个格式化器会重写convert_field
这个方法。
假设你的自定义格式化器cf
使用转换代码l
来格式化列表,这样就可以生成你给出的例子输出:
cf.format("{title}\n{subtitle}\n\n{list!l}", title=title, subtitle=sibtitle, list=list)
另外,你也可以先用"\n".join(list)
把列表格式化好,然后再把这个结果传给你正常的模板字符串。
280
你可以使用标准库中的 string 以及它的 Template 类。
假设有一个文件叫 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