【发布时间】:2018-02-24 00:52:48
【问题描述】:
我正在尝试制作一个 Mad Libs 游戏,用户输入在句子中多次出现的单词。目前我发现用户需要多次输入这些相同的单词。
sentence_a = """GENRE_OF_MUSIC was created by PERSON in Middle Earth.
We only know because NUMBER years ago,
MUSICIAN went on an epic quest with only a OBJECT for
company. MUSICIAN had to steal GENRE_OF_MUSIC from PERSON
and did this by playing a game of SPORT as a distraction."""
#Words to be replaced
parts_of_speech = ["MUSICIAN", "GENRE_OF_MUSIC", "NUMBER",
"OBJECT", "PAST_TENSE_VERB", "PERSON", "SPORT"]
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(ml_string, parts_of_speech):
replaced = []
ml_string = ml_string.split()
for word in ml_string:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type in a: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
print play_game(sentence_a, parts_of_speech)
当您运行代码时,我希望用户只输入一次 GENRE_OF_MUSIC 并且让 Mad Libs 语句仅在每次出现时使用该条目。
【问题讨论】:
-
将已经完成的添加到字典中,然后检查它们是否在字典中
-
看看这是不是你要找的东西:stackoverflow.com/questions/25631695/…
标签: python