【问题标题】:Multiple occurrences of same word in Mad Libs game PythonMad Libs 游戏 Python 中多次出现相同的单词
【发布时间】: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 语句仅在每次出现时使用该条目。

【问题讨论】:

标签: python


【解决方案1】:

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

它的工作原理如下:

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))

【讨论】:

    【解决方案2】:

    您没有跟踪替换以处理重复的关键字。

    您可以更改代码以循环访问您的关键字:

    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"]            
    
    def play_game(ml_string, parts_of_speech):    
        for word in parts_of_speech:
            if word in ml_string:
                user_input = raw_input("Type in a: " + word + " ")
                ml_string = ml_string.replace(word, user_input)
        return ml_string
    
    print play_game(sentence_a, parts_of_speech)
    

    【讨论】:

    • 感谢 Eric,感谢其他所有人,我将与其他人一起试验,并确保在未来的项目中使用它们!
    • 谢谢,我试图让我的答案尽可能接近您的原始代码,以便更容易理解。我建议了解其他答案,我喜欢Hugh's
    【解决方案3】:

    你的代码没必要太复杂。

    首先,您可以要求用户替换词性。您可以通过 parts_of_speech 循环来做到这一点,并将每个用户输入存储到映射中:

    parts = {}
    for replacement in parts_of_speech:
        user_input = raw_input("Type in a " + replacement + ": ")
        parts[replacement] = user_input
    

    然后您可以拆分句子并通过用户替换替换每个单词(如果存在)。如果没有,你信守诺言:

    words = [parts.get(word, word)
             for word in ml_string.split()]
    return " ".join(words)
    

    你得到:

    Type in a MUSICIAN: Bach
    Type in a GENRE_OF_MUSIC: piano
    Type in a NUMBER: 23
    Type in a OBJECT: roller
    Type in a PAST_TENSE_VERB: dig
    Type in a PERSON: Mr president
    Type in a SPORT: football
    piano was created by Mr president in Middle Earth. We only know because 23 years ago, Bach went on an epic quest with only a roller for company. Bach had to steal piano from Mr president and did this by playing a game of football as a distraction.
    

    注意:word_in_pos函数没用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多