我有一个包含2列的excel文件(第1列=单词,第2列=线索)。我要做的是使用熊猫,随机选择一个工作表'字'列,打印它的线索(从第2列)和创建一个刽子手游戏。 如果不打印线索部分,我下面的代码可以正常工作,但我无法完成的是打印随机选择的单词对应的线索。你知道怎么做吗??在
import random
import pandas as ps
df1=ps.read_excel("C:/Python27/hangman_clues.xlsx")
#Randomly select a word from the 'Word' Column and convert to lowercase
word=random.choice(df1["Word"]).lower()
print "Welcome to Hangman"
print "Your Clue is"
#This is where I want to print the clue from 2nd column based on the
randomly selected word which I am unable to accomplish. Tried
df2=df1.set_index("Word",drop=False) but did not help much.
#below code works fine
guessedword=list('_'*len(word))
ctr=0
while ctr<len(word)+5:
guessedchar=raw_input("Guess a char:")
if guessedchar in word:
getindex=[i.start() for i in re.finditer(guessedchar,word)]
for index in getindex:
guessedword[index]=guessedchar
getindex=[]
guessword="".join(guessedword)
print str(guessedword)
if word==guessword:
print "you win"
break
ctr=ctr+1
您可以使用
df1.sample(n=1)
,它将返回一个随机选择行的数据帧。在你可以得到一个随机索引,并将其用于单词和相应的线索。在
相关问题 更多 >
编程相关推荐