首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么它不接受隐藏的单词?

为什么它不接受隐藏的单词?
EN

Stack Overflow用户
提问于 2019-06-20 01:32:20
回答 2查看 69关注 0票数 0

我创建了一个函数,它接收一个单词,并在包含字典中所有单词的文件中检查该单词,如果找到则接受该单词,否则将打印一条错误消息并再次询问该单词

代码语言:javascript
运行
复制
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')

如果我在第一个输入中写了一个正确的单词,它可以完美地工作,但之后它会按预期循环,但它不接受输入,因为如果我在第一个输入中写了相同的单词,它就会工作并被接受

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-20 01:37:11

代码语言:javascript
运行
复制
file.readlines()

只能调用一次,当您尝试在同一打开的文件上再次调用它时,它将失败。

解决方案:在循环之前读取这些行,并将它们保存到一个变量中:

代码语言:javascript
运行
复制
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

票数 7
EN

Stack Overflow用户

发布于 2019-06-20 01:48:18

更好的方法是将文件转换为set一次,然后使用in检查输入是否存在:

代码语言:javascript
运行
复制
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")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56673107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档