我想寫一個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'
但我不明白,我敢肯定這件事情很明顯,如果任何人能解釋一個解決方案,我會非常感激!
看看[問]。如果你想添加一些東西到你的問題,只需編輯問題並添加它。 – pvg
你還可以修復縮進嗎?發佈的代碼根本不起作用 – pvg