我创建了一个函数,该函数接收一个单词并在包含字典中所有单词的文件中对其进行检查,如果找到该单词,则接受该单词,否则会打印错误消息并再次询问该单词
COUNT(DISTINCTUSER_ID) QUERY
1 1 QUERY_2
2 4 QUERY_1
如果我在第一个输入中输入了正确的单词,它会很好地工作,但是此后的一段时间它会按预期循环,但是考虑到如果我在第一个输入中输入了相同的单词,它将不会起作用并被接受
答案 0 :(得分:7)
nextLine
只能被调用一次,当您尝试在同一打开的文件上再次调用它时,它将失败。
解决方案:在循环读取行并将其保存到变量之前:
file.readlines()
此外,正如奥斯卡·洛佩斯(ÓscarLópez)在他(现已删除)的回答中所提到的:如果您希望游戏在发现一个单词后继续进行,则不应该def getHiddenWord():
file = open('dictionary.txt')
lines = file.readlines() # <-- here
file.close() # <-- here
found = False
while found == False:
hiddenWord = input('Enter the hidden word')
for word in lines: # <-- and here
if word.strip().lower() == hiddenWord.lower():
found = True
print(hiddenWord.lower() + ' found!') # <-- here
break
else:
print('I don\'t have this word in my dictionary please try another word')
-只需打印“成功”和return
答案 1 :(得分:1)
更好的方法是将文件一次转换为set
,而只需使用in
来检查输入是否存在:
def get_hidden_word():
with open('dictionary.txt') as fp:
words = set(w.strip().lower() for w in fp)
while True:
guess = input('Enter the hidden word').strip().lower()
if guess in words:
return guess
print("I don't have this word in my dictionary please try another word")