简体   繁体   English

查询字典用户输入无限循环python

[英]Querying a dictionary user input infinite loop python

Newbie trying to learn some basic python, I've imported a json file containing a dictionary of terms.新手试图学习一些基本的 python,我已经导入了一个包含术语字典的 json 文件。 I'm trying to create a script that lets users look up definitions from my dictionary.我正在尝试创建一个脚本,让用户从我的字典中查找定义。 I'm getting stuck on lines 14-15.我卡在第 14-15 行。 I don't want the script to stop after just two attempts.我不希望脚本在两次尝试后停止。 I can work out how to set it to a max # of attempts but not how to make it infinite allowing unlimited tries.我可以弄清楚如何将其设置为最大尝试次数,但不知道如何使其无限允许无限次尝试。 Each new query should be followed by a close match result using the get_close_matches method in difflib if the attempt is not an exact match, with the user prompted to accept or reject the closest match.如果尝试不是完全匹配,则每个新查询后都应使用 difflib 中的 get_close_matches 方法获得接近匹配结果,并提示用户接受或拒绝最接近的匹配。 My script, however, will stop after two attempts and if the 2nd query is not an exact match error out instead of presenting the 3 (the default for the method) closest matches to the word.但是,我的脚本将在两次尝试后停止,并且如果第二个查询不是完全匹配错误,而不是显示与该单词最接近的 3 个(该方法的默认值)匹配项。 Any ideas?有任何想法吗?

import json
from difflib import get_close_matches


data=json.load(open('data.json'))

def translate(w):
    w=w.lower()
    if w in data:
        return data[w]
    elif len(get_close_matches(w,data.keys()))>0:
        yn=input("Did you mean %s? Enter Y or N: " % get_close_matches(w,data.keys())[0]).upper()
        while yn =="N":
            i=input("Enter Word: ")
            return data[get_close_matches(i,data.keys())]

        else:
            return data[get_close_matches(w,data.keys())[0]]

word=input("Enter Word: ")

print(translate(word))

Your current approach isn't working because of the return statement inside the while yn == "N" loop.由于while yn == "N"循环中的return语句,您当前的方法不起作用。 That return immediately takes you out of the function, regardless of whether the loop has completed, so there's no way for this loop to run more than once.无论循环是否完成,该return都会立即将您带出 function,因此该循环无法多次运行。

You could edit the loop to prevent it from always returning, but it's easier to move the loop outside the function.您可以编辑循环以防止它总是返回,但将循环移到 function 之外更容易。 That way you don't have to worry about whether you're working with the initial input or a subsequent input, and you can cut down on duplicate code:这样您就不必担心是使用初始输入还是后续输入,并且可以减少重复代码:

def translate():
    w = input("Enter Word: ").lower()
    if w in data:
        return data[w]

    close_matches = get_close_matches(w, data.keys())  # This only runs if w was NOT in data

    if len(close_matches) > 0:
        yn = input("Did you mean %s? Enter Y or N: " % close_matches[0]).upper()
        if yn == 'Y':
            return data[close_matches[0]]

    return None  # This is optional. Reaching the end of a function will return None by default


translated_word = None  # Force at least one iteration of the loop
while translated_word is None:  # Keep going until there's a match or the user types "Y"
    translated_word = translate()  

print(translated_word)  # This will only run once the loop condition is False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM