2014-11-24 2 views
-2

저는 파이썬에서 임의의 단어를 선택하도록하는 방법에 조금 갇혀 있습니다. 사용자는 올바른 단어가 표시되어야하는 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'개체가 어떤 속성 '선택' –

+1

가 없습니다를 @ 먼저, 봇은''임의 가져 오기 * ''와 같이 가져 오기를해야하며 그렇게하면''choice()' '를 호출해야합니다. 이를 수행하는 더 좋은 방법은''import random''과''random.choice()''를 사용하는 것입니다. – go2

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") 
관련 문제