首页 > 解决方案 > 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”我不知道当我在第一次。感谢您的帮助

标签: python

解决方案


这部分代码有问题:

    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 : ")

推荐阅读