在 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”中的元素插入到从文件中提取的字符串中。
但是,事实并非如此,我已经没有主意了。有什么帮助吗?
最佳答案
确保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
关于Python:将未知大小的数组插入字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131585/