从疯狂的句子选择python中选择

时间:2017-09-14 21:13:18

标签: python loops while-loop

我正在尝试编写一个Madlibs游戏,用户可以选择三个句子中的一个来玩。当我只使用一个时,我能够让它工作,但我试图实现一个循环来分配一个句子选择,这就是问题的开始!

#Sentences for THE GREAT SENTENCE CREATION GAME
sentence_a = """My best memory has to be when MUSICIAN and I
            PAST_TENSE_VERB through a game of SPORT. Then we
            listened to GENRE_OF_MUSIC with PERSON. It was insane!!"""

sentence_b = """Did you know, MUSICIAN once PAST_TENSE_VERB on a
            OBJECT for NUMBER hours. Not many people know that!"""

sentence_c = """GENRE_OF_MUSIC was created by PERSON in Middle Earth.
            We only know GENRE_OF_MUSIC because NUMBER years ago,
            MUSICIAN went on an epic quest with only a OBJECT for
            company. MUSICIAN had tosteal GENRE_OF_MUSIC from PERSON
            and did this by playing a game of SPORT as a distraction."""
#GAME START

def get_sentence():
    choice = ""
    while choice not in ('a', 'b', 'c'):
        choice = raw_input("select your sentence: a, b, or c: ")
        if choice == "a":
            return sentence_a
        elif choice == "b":
            return sentence_b
        elif choice == "c":
            return sentence_c
        else:
            print("Invalid choice...")

#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

# Plays a full game of mad_libs. A player is prompted to replace words in ml_string, 
# which appear in parts_of_speech with their own words.  
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) 

所以我得到的错误是:

Traceback (most recent call last):
  File "Project.py", line 75, in <module>
    print play_game(get_sentence, parts_of_speech)
  File "Project.py", line 63, in play_game
    ml_string = ml_string.split()
AttributeError: 'function' object has no attribute 'split'

但我不明白,我确定它是显而易见的,所以如果有人能解释一个解决方案我会非常感激!!

1 个答案:

答案 0 :(得分:0)

你有一个轻微的语法问题,你忘了get_sentence上的()告诉它它是一个函数。

print play_game(get_sentence(), parts_of_speech)

你需要get_sentence上的()来做你想做的事。