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

如何实现单词字典持久化?添加单词后重启仍可查询

Fixing Your Persistent Word Dictionary Program

Got it, let's get your word dictionary working so it keeps added words even after you restart the program. Your current code has a couple of small issues—like a misdefined add_word function and no way to save data long-term. Here's a complete, working solution tailored to your needs:

Step 1: Add Persistent Storage with JSON

To make sure your words stick around after closing the program, we'll save the dictionary to a JSON file (e.g., word_dictionary.json). Python's built-in json module makes reading/writing this file straightforward, and it preserves special characters like the Å in BOKMÅL perfectly.

Step 2: Clean Up the add_word Function

Your original function had unnecessary self (used for class methods, not standalone functions) and an unused var parameter. We'll simplify it to take the word pair, update the dictionary, and save changes right away.

Complete Working Code

import json

# Load existing words from file (or start fresh if file doesn't exist)
def load_dictionary():
    try:
        with open("word_dictionary.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        # Start with your default word if no file exists
        return {"ikkje": "ikke"}

# Save the updated dictionary to file
def save_dictionary(word_dict):
    with open("word_dictionary.json", "w", encoding="utf-8") as f:
        json.dump(word_dict, f, ensure_ascii=False, indent=4)

# Add a new word pair to the dictionary and save changes
def add_word(word_dict, nynorsk_word, bokmal_word):
    word_dict[nynorsk_word] = bokmal_word
    save_dictionary(word_dict)
    print(f"Successfully added: {nynorsk_word} → {bokmal_word}")

# Main program flow
if __name__ == "__main__":
    # Load saved words first
    word = load_dictionary()
    
    # Get user input for new word pair
    nynorsk = input("WRITE THE 'NYNORSKE' WORD NOW: ")
    bokmal = input("WRITE THE SAME WORD IN 'BOKMÅL' NOW: ")
    
    # Add the new word and persist it
    add_word(word, nynorsk, bokmal)
    
    # Optional: Show the full dictionary to confirm changes
    print("\nUpdated Dictionary:")
    for ny_word, bok_word in word.items():
        print(f"{ny_word} → {bok_word}")

How It Works

  • Loading Saved Words: The load_dictionary function checks if the JSON file exists. If it does, it loads all previously added words; if not, it starts with your default {"ikkje": "ikke"}.
  • Saving Changes: Every time you add a new word, add_word updates the in-memory dictionary and immediately writes the full dictionary to the JSON file—so no changes are lost if the program closes.
  • UTF-8 Support: We use encoding="utf-8" and ensure_ascii=False to handle Nordic characters correctly, so words with Å/Æ/Ø won't get mangled.

Now, every time you run the program, it will load all your saved words, and any new pairs you add will stay there even after you restart.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:08:03