我是 python 新手,我正在尝试从存储在字典中的几个列表中选择随机单词。我正在编写一个没有用户输入的基于故事的 MadLib。我想要一些词根据出现的随机选择给我不同的列表结果。但是我在编写代码时遇到了麻烦。
我尝试在 GET_WORD 函数中编写 IF 语句,但没有好的结果。任何帮助都会很有用。谢谢:)
试过这个:
if local_dict['opt1'].pop("case B):
case B()
并尝试了这个:
def create_story():
local_dict = copy.deepcopy(word_dict)
return story.format(
get_word('opt1',local_dict),
if get_word('opt1',local_dict)=get_word('opt1',local_dict(2)):
return word_dict_opt1B(),
get_word('opt2',local_dict),
get_word('alt1',local_dict)
)
def word_dict_opt1B = {
'opt3': ['case I','case J','case K']
}
编码
import random
import copy
# Inspirert av Mad Libs Random Story Generator
story = (
"ACT I.\n " +
"As you venture into the world. {} calls your attention. Here you encounter {}.\n" +
"Here is your {}"
)
# create a dictionay
word_dict = {
'opt1': ['case A','case B','case C'],
'opt2':['case D','case F','case H'],
'alt1':['alt A.1','alt A.2'],
}
def get_word(type, local_dict):
words = local_dict[type];
cnt = len(words)-1
index = random.randint(0, cnt)
return local_dict[type].pop(index)
def create_story():
local_dict = copy.deepcopy(word_dict)
return story.format(
get_word('opt1',local_dict),
get_word('opt2',local_dict),
get_word('alt1',local_dict)
)
print ("Story 1: ")
print (create_story())
print ("")
print ("Story 2: ")
print (create_story())