我成功运行了以下代码,但是我想知道是否可以 在用户输入一个单词后,将while循环添加到我的代码中,以使我的程序要求另一个单词。
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def meaning(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
answer = input("Did you mean %s instead. Press Y if yes or Press N if no: " % get_close_matches(w, data.keys())[0])
if answer == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif answer == "N":
return "The word doesn't exist. Please Check again."
else:
return "The word doesn't exist in english dictionary."
else:
return "The word doesn't exist. Please Check again."
word = input("Enter a word: ")
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)
input()
我希望程序在用户输入单词并得到结果后要求用户输入另一个单词。
答案 0 :(得分:0)
您可以执行以下操作:
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def meaning(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
answer = input("Did you mean %s instead. Press Y if yes or Press N if no: " % get_close_matches(w, data.keys())[0])
if answer == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif answer == "N":
return "The word doesn't exist. Please Check again."
else:
return "The word doesn't exist in english dictionary."
else:
return "The word doesn't exist. Please Check again."
word = ""
while word != "q":
word = input("Enter a word or q to quit: ")
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)
这将一直循环直到您输入q。我不确定您的json是什么样子,因此您可能需要根据含义函数的功能进行一些修改。
答案 1 :(得分:0)
在请求输入并对其进行处理的代码周围放置while
循环。检查结束字符串,并在获得时跳出循环。
while True:
word = input("Enter a word: ")
if word == 'q':
break
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)