2014-11-24 38 views
-2

我有點卡在如何讓Python選擇一個隨機單詞。 用戶將有5次機會後,它應該顯示正確的單詞。如何讓Python選擇一個隨機單詞

我得到這個作爲一個錯誤

AttributeError的:「builtin_function_or_method」對象有沒有屬性「選擇」

from random import * 


word = ['hello','bye','who','what','when','mouse','juice','phone','touch','pen','book','bag','table','pencil','day','paint','screen','floor','house','roof' ] 

print("You will have 5 chances to guess the correct word! ") 
rounds = 5 

word = random.choice(WORDS) 

correct = word 
length = len(word) 
length = str(length) 

while tries < 5: 
    guess = raw_input("The word is " + length + " letters long. Guess a letter!: ") 
    if guess not in word: 
     print ("Sorry, try again.") 
    else: 
     print ("Good job! Guess another!") 

    tries += 1 

final = raw_input ("Try to guess the word!: ") 

if final == correct: 
    print ("Amazing! My word was ", word, "!") 

else: 
    print("the value to guess was ",word,"\n") 

回答

1

當然,這依賴於字存儲在該文件中,但假設的話都用空格隔開,很容易:

with open("wordguessing.txt") as infile: 
    wordlist = infile.read().split() 
toguess = choice(wordlist) # random.choice() chooses an item from a given iterable 
+0

對不起,我看我的任務錯誤,我不得不在文件中有它,但現在我得到一個錯誤AttributeError的:「builtin_function_or_method」對象有沒有屬性「選擇」 – 2014-11-24 17:33:21

+1

@起點首先,你應該像從''隨機導入*''一樣導入bot,當你這樣做時,你應該調用''choice()''。更好的方法是使用''import random''然後''random.choice()''。 – go2 2014-11-24 17:36:52

0

嘗試使用random.choice代替random.randint。第二個函數將返回一個介於0和len之間的數字,而不是一個單詞。

我重寫你的代碼只是爲了顯示random.choice。還有更多的事情,以改善:)

import random 
myList =['hello','bye','who','what','when','mouse','juice','phone','touch','pen','book','bag','table','pencil','day','paint','screen','floor','house','roof' ] 

print("You will have 5 chances to guess the correct word! ") 
rounds = 5 
word = random.choice(myList) 
toguess = (input("Enter word here: ")) 
if word == toguess: 
    print("Amazing! You guessed it!") 
else: 
    print("Try again!") 
print("the value to guess was ",word,"\n")