在 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
会起作用,因为它只会将“单词”中的元素插入从文件中提取的字符串中。
但是,它没有,而且我没有想法。有什么帮助吗?