我正试图用python编写一个递归程序,但我似乎无法掌握其逻辑

2024-04-26 13:46:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图编写一个python程序,从字典中收集键并显示其值。我正在使用difflib库中的get_close_匹配,我需要创建一个递归a,在输入“n”表示否后,在字典中显示下一个值。下面是工作代码:

import json
import difflib
from difflib import get_close_matches

data = json.load(open("data.json"))
data_keys = data.keys()

word=input("Enter word to be defined here:\n")

if word.capitalize() in data:
    word=word.capitalize()
elif word.upper() in data:
    word=word.upper()
else:
    word=word.lower()

word=str(word)

def meaning():
    if word in data:
        for i in data[word]:
            print(i+"\n")
    elif len(get_close_matches(word,data_keys)) > 0:
        YorN = input("Do you mean %s ? \nIf it is enter :(y) else enter: (n) \n" % get_close_matches(word,data_keys)[0])
        if YorN in {"y","yes","Y","(y)","(Y)"}:
            for i in data[str(get_close_matches(word,data_keys)[0])]:
                print(i+"\n")
        elif YorN in {"n","no","N","(n)","(N)"}:
            YorN1 = input("Do you mean %s ? \nIf it is enter :(y) else enter: (n) \n" % get_close_matches(word,data_keys)[1])
            if YorN1 in {"y","yes","Y","(y)","(Y)"}:
                for i in data[str(get_close_matches(word,data_keys)[1])]:
                    print(i+"\n")
            elif YorN1 in {"n","no","N","(n)","(N)"}:
                YorN2 = input("Do you mean %s ? \nIf it is enter :(y) else enter: (n) \n" % get_close_matches(word,data_keys)[2])
                if YorN2 in {"y","yes","Y","(y)","(Y)"}:
                    for i in data[str(get_close_matches(word,data_keys)[2])]:
                        print(i+"\n")
                else: print("Sorry couldn't find this word, ensure the spelling is correct!")
        else : print("Sorry couldn't find this word, ensure the spelling is correct!")
    else : print("Sorry couldn't find this word, ensure the spelling is correct!")

meaning()

我希望我可以有一个递归代码,它更有效,而不必重复同一行代码。对所有的py大师,请对我放松点,我是个新手


Tags: incloseinputdatagetifiskeys
1条回答
网友
1楼 · 发布于 2024-04-26 13:46:42
def nextClosestMatch(attempt):
    YorN = input("Do you mean %s ? \nIf it is enter :(y) else enter: (n) \n" %
             get_close_matches(word, data_keys)[attempt])
    if YorN in {"y", "yes", "Y", "(y)", "(Y)"}:
        for i in data[str(get_close_matches(word, data_keys)[attempt])]:
            print(i+"\n")
    elif YorN in {"n", "no", "N", "(n)", "(N)"}:
        nextClosestMatch(attempt+1)
    else:
        print("Sorry couldn't find this word, ensure the spelling is correct!")

def meaning():
    if word in data:
        for i in data[word]:
            print(i+"\n")
    elif len(get_close_matches(word, data_keys)) > 0:
        nextClosestMatch(0)

我认为这就是你要寻找的,如果没有找到正确的项目,它会称自己在寻找下一个最接近的匹配项

相关问题 更多 >