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 

会起作用,因为它只会将“单词”中的元素插入从文件中提取的字符串中。

但是,它没有,而且我没有想法。有什么帮助吗?

4

2 回答 2

1

确保words是一个元组:

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

顺便说一句,MadLib 有时会重复提供的相同单词。因此,制作wordsadict而不是list. 然后你可以做这样的事情:

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 回答