我刚刚开始学习Python,作为一个有趣的练习,一个朋友让我写一个程序:从一个单独的文件中随机选取一个关键字,将所选的关键字与字典中的关键字进行比较,然后打印一个包含关键字和附加信息的字符串(我们称之为“定义”)。它应该取一个词,通过在前面加上辛辛那提这个词,把它变成委婉语,然后给出定义。我写的代码如下所示。
import random
def cincinnati_word():
list = open("cincinnati_stuff.txt").read().splitlines()
word = random.choice(list)
return word
cincinnati_dict = {
'car wash': 'you slip and slide through the legs of at least three hookers while they pee on you',
'sweat sock': 'you get your whole foot into an orifice on someone else\'s body. Gettin\' in above the ankle makes it a tube sock',
'hot pocket': 'you stick a lit firecracker into someone\'s pocket',
'rest home': 'they make the dog chow',
'Eggo waffle': 'you\'re having sex with someone and you press a tennis racket over his/her face and scream "Leggo my Eggo!"',
'slip \'n slide': 'a kid throws up in the hallway at school',
'dust mop': 'you don\'t trim your pubic hair at all',
'prom date': 'a hooker agrees to the barter system of payment',
'double dip': 'you get two VD\'s from the same partner at the same time',
'dog park': 'the PETA shelter throws all the carcasses of the dogs they put down',
'soda stream': 'you fart into someone\'s drink through a straw',
'gramophone': 'someone blows a trumpet real loud in your ear',
'tail pipe': 'you put a gerbil up your butt with a paper towel roll',
}
for word, meaning in cincinnati_dict.items():
word = cincinnati_word()
new_word = cincinnati_dict.get(word)
if new_word:
print "The Cincinnati Kid: \"The old Cincinnati %s, yeah, that's where %s.\"" % (word, meaning)
break
else:
print "The Cincinnati Kid: \"The Cincinnat %s? That ain't no thing I ever hoid of." %(word)
break给我带来麻烦的是这段代码能正常工作...差不多了。它成功地从文本文件中检索到一个关键字。它成功地将其与字典中的键列表进行了比较。它还成功地从字典中返回一个定义。问题是,无论使用哪个关键字,返回的定义都是相同的。到目前为止,在我运行的每个测试中,它总是返回辛辛那提留声机的定义。
我相信答案是显而易见的,但我已经盯着这个看了几天了,我看不出是什么导致了这一点。有人能给点建议吗?我要提前表示感谢。
发布于 2016-04-13 11:00:22
在不需要的时候使用循环(for word, meaning in cincinnati_dict:)。无条件的break是一个提示,你根本不想要循环。
相反,只要在get调用和if条件中使用meaning而不是new_word:
word = cincinnati_word()
meaning = cincinnati_dict.get(word)
if meaning:
print "The Cincinnati Kid: \"The old Cincinnati %s, yeah, that's where %s.\"" % (word, meaning)
else:
print "The Cincinnati Kid: \"The Cincinnati %s? That ain't no thing I ever hoid of." %(word)https://stackoverflow.com/questions/36587448
复制相似问题