Python:将未知大小的数组插入到字符串中

时间:2012-04-12 20:49:16

标签: python python-2.7

在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 

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

然而,它没有,我没有想法。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

确保words是一个元组:

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

顺便说一句,MadLib有时会重复相同的提供词。因此,words成为dict而不是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

答案 1 :(得分: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