python - Python:行在输出上执行两次
问题描述
我正在制作一个字典程序,它从 json 文件中定义一个单词并将其输出到控制台。有输出:
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def get_matches(w):
return get_close_matches(w, data, 3, 0.8)
def get_definitions(w):
if w in data:
return data[w]
else:
suggested_words = get_matches(w)
if len(suggested_words) != 0 and w in data:
return get_matches(w)
elif len(suggested_words) != 0 and w != data:
new_input = input("Please check again : ")
while 1:
suggested_words = get_matches(new_input)
if new_input in data or len(suggested_words) == 0 or new_input == 'q':
break
print("Did you mean %s instead ?" % suggested_words)
new_input = input("Please check again (enter q to quit) : ")
if new_input in data and len(suggested_words) != 0:
return data[new_input]
elif new_input == 'q' and len(suggested_words) != 0:
return "You have quit."
else:
return "This word doesn't exist in the dictionary."
else:
return "This word doesn't exist in the dictionary."
word = input("Please enter a word : ").lower()
output = get_definitions(word)
if isinstance(output, list,):
for i in output:
print(i)
else:
print(get_definitions(word))
代码正在运行,但是当我想输入“q”退出程序时我遇到了一个小问题,我收到另一个输入“q”我不知道当我在第一次。感谢您的帮助
解决方案
这部分代码有问题:
if len(suggested_words) != 0 and w in data:
return get_matches(w)
elif len(suggested_words) != 0 and w != data:
new_input = input("Please check again : ")
第一个 if 从不返回 True 因为在这个分支中 2 从不在数据中。
你应该有:
if len(suggested_words) != 0:
return get_matches(w)
new_input = input("Please check again : ")
推荐阅读
- jquery - Jquery 数据表:如何在每行的最后一个单元格中添加一个按钮,
- stm32 - 初始化 ST-Link 设备时出错。原因:ST-Link DLL错误
- python - Selenium 和 OSX - 自动化系统提示
- gremlin - 动态 gremlin 遍历构造
- css - (基础)网格单元突破与背景图像
- python - 从 Python 命令行复制/粘贴到 sublime
- ruby-on-rails - Ruby on Rails 表单未在选择多个字段中捕获值
- r - R中卡方的置信区间
- arrays - 用 scipy.stats 拟合线性回归;数组形状错误
- javascript - css在右侧对齐多行contenteditable内容