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

Python英德词典代码优化咨询与查询功能问题排查

英德词典查询功能故障排查与优化建议

问题概述

  • 目标:开发一款支持添加新词和查询已有翻译的英德词典
  • 实现思路:用Python字典存储(英文为键,德语为值),将字典转为字符串写入文本文件持久化
  • 核心问题:添加功能正常,但查询功能无法正确获取翻译,同时不确定当前编码/存储方式是否适合实际项目

原代码核心问题分析

  1. 输入判断逻辑错误:if i == 1 or 2 中,i 是用户输入的字符串(比如"1"),和数字1/2永远不相等,导致这部分逻辑根本不会执行,直接走到else分支提示选1或2
  2. 文件读取逻辑完全错误:查询时将文件对象直接赋值给new_dict,循环中又把lines重置为空字典,完全没有从文件中解析出原本的字典数据
  3. 字典取值判断错误:lines.get(word) == -1 是错误的,字典的get()方法在键不存在时返回None,不是-1
  4. 递归调用隐患:每次操作后递归调用eng_ger_dict(),多次操作会导致栈溢出
  5. 文件管理不规范:打开文件后未正确关闭,且使用w模式会清空文件内容,若程序意外终止可能丢失数据
  6. 存储格式不合理:直接将字典转为字符串存储,解析时容易出错,且不具备跨语言可读性

修复后的代码实现

使用json模块进行字典的序列化与反序列化(比直接转字符串更可靠),同时修复输入判断、文件读取逻辑,用循环代替递归:

import json

def eng_ger_dict(f_name):
    # 初始化字典,先从文件加载已有数据
    eng2ger = {}
    try:
        with open(f_name, 'r', encoding='utf-8') as f:
            eng2ger = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        # 文件不存在或解析失败时,初始化空字典
        pass

    while True:
        choice = input("(1) Add new word\n(2) Look for the translation\n...Type 'done' to exit.\n->enter the option: ").strip().lower()
        if choice == 'done':
            print("Exiting...")
            break
        
        # 验证输入是否为有效选项
        if not choice in ['1', '2']:
            print("Please select option 1 or 2, or type 'done' to exit.\n")
            continue
        
        inp = int(choice)
        if inp == 1:
            eng = input("Enter english word: ").strip()
            ger = input("Enter german version: ").strip()
            if eng and ger:  # 避免空输入
                eng2ger[eng.lower()] = ger.lower()  # 统一小写,避免大小写敏感
                print(f"Added: {eng} -> {ger}\n")
                # 写入文件,用utf-8编码确保支持特殊字符
                with open(f_name, 'w', encoding='utf-8') as f:
                    json.dump(eng2ger, f, indent=2, ensure_ascii=False)
            else:
                print("English and German words cannot be empty.\n")
        
        elif inp == 2:
            word = input("Enter the english word to get the german version: ").strip().lower()
            translation = eng2ger.get(word)
            if translation:
                print(f"German translation: {translation}\n")
            else:
                print(f"German version of '{word}' does not exist. Use option 1 to add it.\n")

# 启动程序
eng_ger_dict("eng2ger.json")  # 改用json后缀更清晰

优化建议

  • 使用JSON格式存储:相比直接转字符串,JSON是标准的数据交换格式,解析更可靠,支持跨语言读取,且json模块提供了完善的序列化/反序列化方法
  • 用with语句管理文件:自动处理文件的打开与关闭,避免资源泄漏
  • 统一大小写处理:将输入的单词转为小写存储和查询,避免因大小写不同导致的查询失败(比如"One"和"one"视为同一个词)
  • 避免递归调用:用while True循环代替递归,防止多次操作后栈溢出
  • 输入验证增强:检查用户输入是否为空,避免无效数据存入字典
  • 编码规范:指定encoding='utf-8',确保支持德语中的特殊字符(比如ä、ö、ü)
  • 错误处理:捕获文件不存在、JSON解析失败等异常,提升程序稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:01:07