gpt4 book ai didi

python - Python中是否有用于纯文本文件的 native 模板系统?

转载 作者:IT老高 更新时间:2023-10-28 20:27:50 25 4
gpt4 key购买 nike

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

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

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

通过模板运行,输出将如下所示:

Foo
Bar

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

如何做到这一点?谢谢。

最佳答案

您可以使用标准库 string一个它的模板类。

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

关于python - Python中是否有用于纯文本文件的 native 模板系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6385686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com