2014-11-24 133 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")