You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python交互式词典:查询崩溃修复及相似词推荐功能实现

Python命令行词典问题修复与相似词功能实现

现有代码崩溃原因

你输入不存在单词时程序中断,核心问题是判断逻辑写错:
term_data.get(SearchItems, True) 会在key不存在时返回默认值True,导致第一个if分支永远成立。当搜索词不在词典里时,后续执行term_data[SearchItems]会直接触发KeyError崩溃,永远走不到你写的错误提示分支。另外每次查询都重复读取JSON文件、用递归做循环查询也会有性能和栈溢出隐患。

可直接运行的修复后代码

import json

# 词典文件仅启动时加载一次,避免每次查询重复读盘
with open('Dictionary.json', 'r', encoding='utf-8') as f:
    term_data = json.load(f)

def get_similar_words(input_word, all_words, max_diff=2):
    """无第三方依赖的相似词匹配,覆盖拼写错误、前缀缩写场景"""
    similar_res = []
    input_low = input_word.strip().lower()
    for word in all_words:
        word_low = word.lower()
        # 前缀/子串匹配:覆盖记不全单词、输缩写的场景
        if input_low in word_low or word_low.startswith(input_low[:min(3, len(input_low))]):
            similar_res.append(word)
            continue
        # 等长单词:统计不同字符数,匹配错1-2个字母的情况
        len_diff = abs(len(input_low) - len(word_low))
        if len_diff == 0:
            diff_count = sum(1 for a, b in zip(input_low, word_low) if a != b)
            if diff_count <= max_diff:
                similar_res.append(word)
        # 长度差1:匹配多打/漏打1个字母的情况
        elif len_diff == 1:
            longer, shorter = (input_low, word_low) if len(input_low) > len(word_low) else (word_low, input_low)
            for i in range(len(longer)):
                if longer[:i] + longer[i+1:] == shorter:
                    similar_res.append(word)
                    break
    return list(set(similar_res))

def search():
    while True:
        search_item = input("Enter search: ").strip()
        # 单词存在直接输出释义
        if search_item in term_data:
            print(f"{search_item} - {term_data[search_item]}")
        # 单词不存在走错误提示+相似词逻辑
        else:
            print("not a word in the dictionary or invalid value entered.")
            sim_choice = input("would you like to find similar words? y/n: ").strip().lower()
            if sim_choice == "y":
                sim_words = get_similar_words(search_item, term_data.keys())
                if not sim_words:
                    print("No similar words found in current dictionary.")
                else:
                    print("Possible matching words:")
                    for idx, word in enumerate(sim_words, 1):
                        print(f"{idx}. {word}")
                    pick = input("Enter the serial number to select the word to query, press other keys to skip: ").strip()
                    if pick.isdigit() and 1 <= int(pick) <= len(sim_words):
                        target = sim_words[int(pick)-1]
                        print(f"{target} - {term_data[target]}")
        # 处理下一轮查询判断
        next_choice = input("Would you like to search the meaning of a new word? y/n: ").strip().lower()
        if next_choice != "y":
            print("Okay Goodbye")
            break

if __name__ == "__main__":
    start_choice = input("Would you like to Search for a word, y/n? :  ").strip().lower()
    if start_choice == "y":
        search()
    else:
        print("Okay Goodbye")

改动说明

  • 修复了原逻辑中get默认值设置错误导致的KeyError崩溃问题,不存在的搜索词会正常触发错误提示
  • 所有输入增加首尾空格过滤、大小写统一处理,避免用户误输入空格、大写导致匹配失败
  • 将原递归查询逻辑改为while循环,避免多次查询后触发递归深度溢出
  • JSON词典文件仅在程序启动时加载一次,查询响应速度更快
  • 相似词功能无需安装第三方库即可使用,覆盖三类常见输入错误场景:拼写错1-2个字母、多打/漏打1个字母、只记得单词前缀/部分拼写,匹配到结果后支持用户直接选号查询,不用重复输入。如果需要更高精度的模糊匹配,可以后续根据需求调整匹配阈值。

内容的提问来源于stack exchange,提问作者Megan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 06:27:24