【发布时间】:2020-11-01 11:18:59
【问题描述】:
我是编程新手(已经 1 周了),我制作了一个英语词库程序,它会询问您想要定义的单词并弹出该单词的定义,然后循环返回开始。当你被问到你想要定义哪个词时,你可以输入 \exit 并停止程序。但是,它在程序的后期阶段不起作用。例如:
Enter a Word or Type (\exit) to Exit: rainn
Did You Mean 'rain'? (y) for YES and (n) for NO: n
The Word 'rainn' Does Not Exist! Please Try Again: \exit
这里会提示
Did You Mean 'exit'? (y) for YES and (n) for NO: n
它应该在哪里停止程序。
帮帮我,我绝望了,我尽我所能。
程序代码如下:
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
while True:
keyword = input("Enter a Word or Type (\exit) to Exit: ")
if keyword == "\exit":
break
elif keyword.lower() in data:
output = data[keyword.lower()]
if isinstance(output, list):
for definition in output:
print("\"%s\"" % definition)
else:
print("\"%s\"" % definition)
elif keyword.title() in data:
output = data[keyword.title()]
if isinstance(output, list):
for definition in output:
print("\"%s\"" % definition)
else:
print("\"%s\"" % definition)
elif keyword.upper() in data:
output = data[keyword.upper()]
if isinstance(output, list):
for definition in output:
print("\"%s\"" % definition)
else:
print("\"%s\"" % definition)
elif len(get_close_matches(keyword.lower(), data.keys())) > 0:
correction = input(
"Did You Mean %s? (y) for YES and (n) for NO: " % (get_close_matches(keyword.lower(), data.keys())[0]).capitalize())
while True:
if correction.lower() == "y":
output = data[get_close_matches(keyword.lower(), data.keys())[0]]
if isinstance(output, list):
for definition in output:
print("\"%s\"" % definition)
else:
print("\"%s\"" % definition)
break
elif correction.lower() == "n":
# giving input "\exit" won't work here where it's supposed to
keyword = input("The Word '%s' Does Not Exist! Please Try Again or Type (\exit) to Exit: " % keyword)
break
else:
correction = input("Unrecognized Input! Please Try Again: ")
else:
# giving input "\exit" won't work here too
keyword = input("The Word '%s' Does Not Exist! Please Try Again or Type (\exit) to Exit: " % keyword)
【问题讨论】:
-
请将其减少并增强为预期的MRE。显示中间结果与预期结果的偏差。不接受站外链接。
-
@Prune 好的,我下次会更加小心。这是我第一次问堆栈溢出问题。
-
明白——我们都是你。只需重复介绍导览,注意“如何提问”和“MRE”部分,并适当更新。
-
我有空的时候就可以了。顺便说一句,什么介绍导览,因为我不记得了。
标签: python python-3.x loops while-loop conditional-statements