简体   繁体   中英

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. I'm trying to create a script that lets users look up definitions from my dictionary. I'm getting stuck on lines 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. 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. 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. 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.

You could edit the loop to prevent it from always returning, but it's easier to move the loop outside the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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