我创建了一个函数,它接收一个单词,并在包含字典中所有单词的文件中检查该单词,如果找到则接受该单词,否则将打印一条错误消息并再次询问该单词
def getHiddenWord():
file = open('dictionary.txt')
found = False
while found == False:
hiddenWord = input('Enter the hidden word')
for word in file.readlines():
if word.strip().lower() == hiddenWord.lower():
found = True
return hiddenWord.lower()
break
else:
continue
print('I don\'t have this word in my dictionary please try another word')如果我在第一个输入中写了一个正确的单词,它可以完美地工作,但之后它会按预期循环,但它不接受输入,因为如果我在第一个输入中写了相同的单词,它就会工作并被接受
发布于 2019-06-20 01:37:11
file.readlines()只能调用一次,当您尝试在同一打开的文件上再次调用它时,它将失败。
解决方案:在循环之前读取这些行,并将它们保存到一个变量中:
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”和break
发布于 2019-06-20 01:48:18
更好的方法是将文件转换为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")https://stackoverflow.com/questions/56673107
复制相似问题