2

Pythonでは、「%s」を使用して配列から文字列に要素を追加しようとしています。

ただし、コンパイル時には、配列のサイズと、補間している文字列は不明です。アイデアは、別のファイルからテキストをプルするmadlibsタイプのスクリプトを作成しているということです。

現在のコード:

from sys import argv

script, input = argv

infile = open(input)

madlibs = eval(infile.readline())
words = []

for word in madlibs:
    words.append(raw_input("Give me a %s: " % word))

print infile.read() % words

したがって、入力ファイルの最初の行にはmadlibの質問が含まれ、後続のテキストにはストーリーが含まれています。これが私が使用している入力ファイルの例です:

["noun", "verb", "verb", "noun"]
There once was a %s named Bill.
He liked to %s all the time.
But he did it too much, and his girlfriend got mad.
She then decided to %s him to get back at him.
He died. It's a sad story.
They buried him. And on his tombstone, they placed a %s.

したがって、理想的な世界では、

print infile.read() % words 

「words」の要素をファイルから取得した文字列に補間するだけなので、機能します。

しかし、そうではなく、私はアイデアがありません。何か助けはありますか?

4

2 に答える 2

1

wordsタプルであることを確認してください:

print(infile.read() % tuple(words))

ちなみに、MadLibは同じ提供された単語を繰り返すことがあります。したがって、の代わりに作成wordsする方が簡単です。次に、次のようなことを行うことができます。dictlist

words = {
    'man' : 'Bill',
    'store' : 'bar',
    'drink' : 'beer',
    'owner' : 'bartender',
    'action' : 'drink',
    }

text = '''
{man} walks into a {store} and orders a {drink}.
The {owner} asks {man} what he would like to {action}
'''

print(text.format(**words))

これは

Bill walks into a bar and orders a beer.
The bartender asks Bill what he would like to drink
于 2012-04-12T20:54:22.257 に答える
1

「そうではない」方法は?エラーメッセージを含めます。考えられる問題は、リストではなくタプルが必要なことです。

>>> print "%s %s %s %s" % ['This','is','a','test']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> print "%s %s %s %s" % ('This','is','a','test')
This is a test
>>> print "%s %s %s %s" % tuple(['This','is','a','test'])
This is a test
于 2012-04-12T20:54:50.207 に答える