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

Gar*_*uth 56 python templates

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

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

title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
Run Code Online (Sandbox Code Playgroud)

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

Foo
Bar

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Run Code Online (Sandbox Code Playgroud)

这该怎么做?谢谢.

Thi*_*hib 181

您可以使用标准库字符串模板:

所以,你有一个文件foo.txt

$title
...
$subtitle
...
$list
Run Code Online (Sandbox Code Playgroud)

和一本字典

d={ 'title':title, 'subtitle':subtitle, 'list':'\n'.join(list) }
Run Code Online (Sandbox Code Playgroud)

然后它很简单

from string import Template
#open the file
filein = open( 'foo.txt' )
#read it
src = Template( filein.read() )
#do the substitution
src.substitute(d)
Run Code Online (Sandbox Code Playgroud)

然后你可以打印 src

当然,正如Jammon所说,你有很多其他好的模板引擎(这取决于你想做什么......标准的字符串模板可能是最简单的)


完整的工作示例

foo.txt的

$title
...
$subtitle
...
$list
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

然后运行example.py

$ python example.py
This is the title
...
And this is the subtitle
...
first
second
third
Run Code Online (Sandbox Code Playgroud)

  • +1解决简单问题的简单方法 (16认同)
  • 使用`$$`来转义并输出`$`. (4认同)

Obe*_*nne 14

如果您更喜欢使用标准库附带的东西,请查看格式字符串语法.默认情况下,它无法像输出示例中那样格式化列表,但您可以使用自定义格式化程序来处理此方法,该格式化程序会覆盖该convert_field方法.

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

cf.format("{title}\n{subtitle}\n\n{list!l}", title=title, subtitle=sibtitle, list=list)
Run Code Online (Sandbox Code Playgroud)

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

  • 以下是如何执行此操作的示例:https://makina-corpus.com/blog/metier/2016/the-worlds-simplest-python-template-engine。一个简单的模板引擎,在 10 行代码中包含循环和条件。 (2认同)

jam*_*mon 12

python有很多模板引擎:Jinja,Cheetah,Genshi .你不会犯任何错误.

  • OP 说的是“本地人”吗?并验证了一些不是的东西! (7认同)