Python:在输出行执行两次

时间:2019-07-03 11:18:00

标签: python

我正在制作一个字典程序,该程序从json文件中获取单词的定义,并将其输出到控制台。 有输出: console output

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”的问题,我不知道这是怎么回事,当我输入“ q”时应该退出' 在第一时间。 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这部分代码有问题:

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