2017-09-14 65 views
2

我想写一个Madlibs游戏,用户可以从中选择三个句子中的一个来玩。我只能使用一个,但我试图实现一个循环来分配一个句子选项,这就是问题的出发点!从madlib中选择一个句子python

#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' 

但我不明白,我敢肯定这件事情很明显,如果任何人能解释一个解决方案,我会非常感激!

+0

看看[问]。如果你想添加一些东西到你的问题,只需编辑问题并添加它。 – pvg

+0

你还可以修复缩进吗?发布的代码根本不起作用 – pvg

回答

0

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

print play_game(get_sentence(), parts_of_speech) 

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

+0

辉煌,谢谢。我不认为这会很简单!我将来一定要记住这一点。感谢Reginol_Blindhop! – jufg

+0

并感谢编辑和解释PVG! – jufg

+0

@reginol很好的答案。它值得一个复选标记,因为缺少'()'是问题所在。但我也想给你一个赞成票。 (你只能得到一张支票,但你可以得到无限数量的upvotes,每个答案。)但是,我不能,因为你说()“告诉它它的功能。”错误消息是''函数'对象没有属性split',所以很显然Python知道这*是一个函数。你可以编辑你的答案,以提供关于()和函数的准确细节?这样的答案对于那些稍后阅读的人来说是准确的。 –