我有点担心如何让python让它选择一个随机单词。 用户将有5次机会显示正确的单词。
我将此视为错误
AttributeError:'builtin_function_or_method'对象没有属性'choice'
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")
答案 0 :(得分:1)
当然,这取决于单词在该文件中的存储方式,但假设单词是用空格分隔的,那很简单:
with open("wordguessing.txt") as infile:
wordlist = infile.read().split()
toguess = choice(wordlist) # random.choice() chooses an item from a given iterable
答案 1 :(得分:0)
尝试使用random.choice而不是random.randint。第二个函数将返回一个介于0和列表之间的数字,而不是单词。
我重写你的代码只是为了显示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")