Skip to main content
 首页 » 编程设计

python之Mad Libs 游戏 Python 中多次出现同一个词

2024年10月01日7zhengyun_ustc

我正在尝试制作一个 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 句子只在每次出现时使用该条目。

请您参考如下方法:

我建议使用字符串格式而不是搜索和替换。

这是它的工作原理:

import string 
from textwrap import dedent 
 
FMT = string.Formatter() 
 
def get_field_names(format_string): 
    """ 
    Return a list of unique field names from the format string 
    """ 
    return sorted(set(p[1] for p in FMT.parse(format_string) if p[1] is not None)) 
 
sentence_a = dedent(""" 
    {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. 
""") 
 
parts_of_speech = get_field_names(sentence_a) 
replace_dict = {pos:pos for pos in parts_of_speech} 
 
# after getting input from player 
replace_dict["MUSICIAN"] = "Chuck Berry" 
 
# show result 
print(sentence_a.format(**replace_dict))