我正试图编写一个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大师,请对我放松点,我是个新手
我认为这就是你要寻找的,如果没有找到正确的项目,它会称自己在寻找下一个最接近的匹配项
相关问题 更多 >
编程相关推荐