如何实现单词字典持久化?添加单词后重启仍可查询
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_dictionaryfunction 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_wordupdates 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"andensure_ascii=Falseto 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

