如何将单词列表加载到3x3网格中?

时间:2016-02-09 10:42:11

标签: python grid

import random
weird_list=open("f:\\weird_list.txt", "r")    
wordlist=weird_list.read()                     #opens, reads and closes the    text file.
weird_list.close()                           
wordlist=wordlist.split()

此代码打开一个包含10个单词的输入文件。

random1 = random.choice(wordlist)        #displays the random words one by one until it opens 9 out of 10.    
wordlist.remove(random1)            

random2 = random.choice(wordlist)  #it does this by removing the word from the file.
wordlist.remove(random2)

random3 = random.choice(wordlist)
wordlist.remove(random3)

random4 = random.choice(wordlist)
wordlist.remove(random4)

random5 = random.choice(wordlist)
wordlist.remove(random5)

random6 = random.choice(wordlist)
wordlist.remove(random6)

random7 = random.choice(wordlist)
wordlist.remove(random7)

random8 = random.choice(wordlist)
wordlist.remove(random8)

random9 = random.choice(wordlist)
wordlist.remove(random9)

文件中的文字是:NIGHT,SMOKE,GHOST,TOOTH,ABOUT,CAMEL,BROWN,FUNNY,CHAIR,PRICE

print ("Let's play guess the word \n I have a random list of words \n the computer will select randomly from the word list leaving you one remaining word to guess.")

它向玩家解释了游戏规则。

print ("I will give you the following words, you then tell me the missing   word: \n", random1, random2, random3, random4, random5, random6, random7,   random8,   random9,)

打印(显示)单词。

wordsstr =''.join(str(x) for x in wordlist)

weirdguess = input("what is the missing word?: ")

while weirdguess != wordsstr: 
   weirdguess == input ("try another word: ")


print ("You guessed correctly. Game over") #ends the while loop

1 个答案:

答案 0 :(得分:0)

您可以使用list-comprehension:

import random
weird_list=open("f:\\weird_list.txt", "r")    
wordlist=weird_list.read() #opens, reads, and closes the text file.
weird_list.close()                           
wordlist=wordlist.split()
random.shuffle(wordlist)
wordstr = wordlist[0]
wordlist = wordlist[1:]
print("\n".join(" ".join(wordlist[x:x+3]) for x in range(0, len(wordlist), 3)))

print("Correct answer: %s" % wordstr)

输出:

NIGHT CHAIR BROWN
PRICE SMOKE GHOST
CAMEL TOOTH ABOUT
Correct answer: FUNNY

注意,我也改变了你的随机数发生器。 random.shuffle()比使用random.choice()自行改组更容易。