web-dev-qa-db-ja.com

Pythonプレーンテキスト出力用のテクニックまたはシンプルなテンプレートシステム

Python出力を単純なテキストにフォーマットするためのテクニックまたはテンプレートシステムを探しています。必要なのは、複数のリストまたは辞書を反復処理できることです。テンプレートをソースコードにハードコーディングする代わりに、別のファイル(output.templなど)に定義できます。

私が達成したい簡単な例として、変数titlesubtitleおよびlistがあります。

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

テンプレートを実行すると、出力は次のようになります。

Foo
Bar

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

これを行う方法?ありがとうございました。

53
Gargauth

Python用のテンプレートエンジンは非常に多くあります。 JinjaCheetahGenshietc 。それらのいずれかを間違えることはありません。

11
jammon

標準ライブラリ 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

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
174
ThibThib

標準ライブラリに同梱されているものを使用する場合は、 format string syntax をご覧ください。デフォルトでは、出力例のようにリストをフォーマットできませんが、 custom Formatter でこれを処理でき、 _convert_field_ メソッド。

カスタムフォーマッタcfが変換コードlを使用してリストをフォーマットすると仮定すると、これは指定された出力例を生成するはずです。

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

または、"\n".join(list)を使用してリストを事前にフォーマットし、これを通常のテンプレート文字列に渡すこともできます。

14
Oben Sonne

シンプルかどうかはわかりませんが、 Cheetah が役に立つかもしれません。

0
Jeannot