2017-09-14 69 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知道這*是一個函數。你可以編輯你的答案,以提供關於()和函數的準確細節?這樣的答案對於那些稍後閱讀的人來說是準確的。 –