2

ランダムな単語を入れた文章のようなものを作成しようとしています。具体的には、次のようなものがあります。

"The weather today is [weather_state]."

[ブラケット] 内のすべてのトークンを検索し、それらを辞書またはリストからランダム化された対応するものと交換するようなことを実行できるようにするには、次のようにします。

"The weather today is warm."
"The weather today is bad."

また

"The weather today is mildly suiting for my old bones."

[bracket] トークンの位置が常に同じ位置にあるとは限らず、次のように文字列に複数の括弧付きトークンが存在することに注意してください。

"[person] is feeling really [how] today, so he's not going [where]."

どこから始めればよいのか本当にわかりません。これは、これでトークン化またはトークンモジュールを使用するための最良のソリューションでもあります。私を正しい方向に向けるヒントは大歓迎です!

編集: 明確にするために、角括弧を使用する必要は実際にはありません。非標準の文字であれば使用できます。

4

3 に答える 3

4

コールバック関数を使用して re.sub を探しています。

words = {
    'person': ['you', 'me'],
    'how': ['fine', 'stupid'],
    'where': ['away', 'out']
}

import re, random

def random_str(m):
    return random.choice(words[m.group(1)])


text = "[person] is feeling really [how] today, so he's not going [where]."
print re.sub(r'\[(.+?)\]', random_str, text)

#me is feeling really stupid today, so he's not going away.   

メソッドとは異なりformat、これにより、プレースホルダーのより高度な処理が可能になることに注意してください。

[person:upper] got $[amount if amount else 0] etc

基本的には、その上に独自の「テンプレート エンジン」を構築できます。

于 2013-05-16T09:38:00.720 に答える
2

メソッドを使用できますformat

>>> a = 'The weather today is {weather_state}.'
>>> a.format(weather_state = 'awesome')
'The weather today is awesome.'
>>>

また:

>>> b = '{person} is feeling really {how} today, so he\'s not going {where}.'
>>> b.format(person = 'Alegen', how = 'wacky', where = 'to work')
"Alegen is feeling really wacky today, so he's not going to work."
>>>

もちろん、この方法は、角括弧から中括弧に切り替えることができる場合にのみ機能します。

于 2013-05-16T09:35:28.200 に答える