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

标签 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 

可以工作,因为它只是将“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/

相关文章:

php - arc lint 命令失败并出现错误 #1

python - scikit-learn 中是否有任何类型的子空间聚类包可用

python - 根据列中的值指定的优先级删除重复索引

将plt文件转换为特定格式的gcode的Python代码

python-2.7 - 在python中的Twython异常中获取错误代码

mysql - MySQL 中的 Python 变量

Python cx_freeze 4.3.4 : Setting targetName causes errors

python - Numpy - 将列数据类型 (dtype) 分配给现有数组

字符串到 SQL IN 参数的 Python 列表

python - NoReverseMatch at/login - LOGIN_URL 或反向功能出错?