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

如何将我的迷你在线图书馆Python代码优化得更专业?

Optimizing Your Mini JSON Library: Function Organization & Code Cleanup

Hey Hugo, awesome work getting your mini online library up and running with JSON storage—this is a really solid second version! Let's walk through how to organize your code into functions, simplify syntax, and make the whole thing more maintainable and user-friendly.

Why Functions Matter for This Project

Right now, your code works, but all the logic is tangled in one big loop. Breaking tasks into functions does three key things:

  • Eliminates repetitive code (like writing to the JSON file multiple times)
  • Makes it easier to fix bugs or add new features later
  • Lets you focus on one task at a time (e.g., "how to load the library" vs. "how to add a book")

Step-by-Step Optimizations & Function Breakdown

Let's split your code into focused functions, then put it all back together.

1. Core File Operations: Load & Save

First, let's wrap the JSON file work into two reusable functions—this way you don't repeat the open()/json.dump() code every time you modify the library:

import json
import os
import tkinter as tk

def load_library(file_path):
    # Create empty library if the file doesn't exist yet
    if not os.path.exists(file_path):
        return []
    with open(file_path, 'r') as f:
        return json.load(f)

def save_library(library, file_path):
    # Add indent to make the JSON file human-readable
    with open(file_path, 'w') as f:
        json.dump(library, f, indent=4)

2. Book Management Functions

Next, split each user action into its own function. This keeps your main loop clean and makes each task easy to tweak.

Add a Book

def add_book(library):
    title = input("Enter the title of your new book: ").strip()
    author = input("Enter the author's name: ").strip()
    new_book = {"book": title, "author": author}
    library.append(new_book)
    print(f"✅ Added '{title}' by {author} to your library!")
  • Used .strip() to clean up accidental extra spaces in user input
  • Added a clear success message instead of printing the whole library

Delete a Book

def remove_book(library):
    title = input("Enter the title of the book to remove: ").strip()
    author = input("Enter the author's name: ").strip()
    book_to_remove = {"book": title, "author": author}
    
    if book_to_remove in library:
        library.remove(book_to_remove)
        print(f"❌ Removed '{title}' by {author} from your library!")
    else:
        print(f"⚠️ '{title}' by {author} isn't in your library—nothing was removed.")
  • Added a check to avoid crashes if the user tries to delete a book that doesn't exist
  • Friendlier feedback messages

Search for a Book

def search_book(library):
    title = input("Enter the title of the book you're searching for: ").strip()
    author = input("Enter the author's name: ").strip()
    target_book = {"book": title, "author": author}
    
    if target_book in library:
        print(f"🎉 You have '{title}' by {author} in your library!")
    else:
        print(f"😞 You don't have '{title}' by {author} in your library.")
  • Cleaned up input handling and made feedback more engaging

3. User-Friendly View Library UI

Your original UI just printed the raw list—let's make it look nicer and handle empty libraries:

def show_library(library):
    window = tk.Tk()
    window.title("Your Mini Library")
    window.geometry("400x300")  # Set a default window size
    
    # Format library content for readability
    if not library:
        library_content = "Your library is empty—add some books first!"
    else:
        library_content = "\n".join([f"- '{book['book']}' by {book['author']}" for book in library])
    
    # Style the UI elements a bit
    content_label = tk.Label(
        window, 
        text=library_content, 
        justify=tk.LEFT, 
        padx=15, 
        pady=15,
        font=("Arial", 10)
    )
    quit_button = tk.Button(
        window, 
        text="Close", 
        fg="red", 
        command=window.destroy,
        font=("Arial", 10)
    )
    
    content_label.pack(expand=True, fill=tk.BOTH)
    quit_button.pack(pady=10)
    
    window.mainloop()

4. Clean Main Menu Loop

Finally, wrap the user choice logic into a main menu function. We'll use elif instead of multiple if statements to avoid accidental multiple actions:

def main_menu(library, file_path):
    while True:
        print("\n" + "="*30)
        print("🎓 Your Online Library")
        print("="*30)
        choice = input("""Choose an option:
1. Add a new book
2. Delete a book
3. View your library
4. Search for a book
5. Exit
Enter your choice (1-5): """)
        
        if choice == "1":
            add_book(library)
            save_library(library, file_path)
        elif choice == "2":
            remove_book(library)
            save_library(library, file_path)
        elif choice == "3":
            show_library(library)
        elif choice == "4":
            search_book(library)
        elif choice == "5":
            save_library(library, file_path)
            print("\n👋 Thanks for using your library—goodbye!")
            break
        else:
            print("\n❌ Invalid choice! Please enter a number between 1 and 5.")

Full Optimized Code

Here's everything put together with a proper entry point:

import json
import os
import tkinter as tk

def load_library(file_path):
    if not os.path.exists(file_path):
        return []
    with open(file_path, 'r') as f:
        return json.load(f)

def save_library(library, file_path):
    with open(file_path, 'w') as f:
        json.dump(library, f, indent=4)

def add_book(library):
    title = input("Enter the title of your new book: ").strip()
    author = input("Enter the author's name: ").strip()
    new_book = {"book": title, "author": author}
    library.append(new_book)
    print(f"✅ Added '{title}' by {author} to your library!")

def remove_book(library):
    title = input("Enter the title of the book to remove: ").strip()
    author = input("Enter the author's name: ").strip()
    book_to_remove = {"book": title, "author": author}
    
    if book_to_remove in library:
        library.remove(book_to_remove)
        print(f"❌ Removed '{title}' by {author} from your library!")
    else:
        print(f"⚠️ '{title}' by {author} isn't in your library—nothing was removed.")

def search_book(library):
    title = input("Enter the title of the book you're searching for: ").strip()
    author = input("Enter the author's name: ").strip()
    target_book = {"book": title, "author": author}
    
    if target_book in library:
        print(f"🎉 You have '{title}' by {author} in your library!")
    else:
        print(f"😞 You don't have '{title}' by {author} in your library.")

def show_library(library):
    window = tk.Tk()
    window.title("Your Mini Library")
    window.geometry("400x300")
    
    if not library:
        library_content = "Your library is empty—add some books first!"
    else:
        library_content = "\n".join([f"- '{book['book']}' by {book['author']}" for book in library])
    
    content_label = tk.Label(
        window, 
        text=library_content, 
        justify=tk.LEFT, 
        padx=15, 
        pady=15,
        font=("Arial", 10)
    )
    quit_button = tk.Button(
        window, 
        text="Close", 
        fg="red", 
        command=window.destroy,
        font=("Arial", 10)
    )
    
    content_label.pack(expand=True, fill=tk.BOTH)
    quit_button.pack(pady=10)
    
    window.mainloop()

def main_menu(library, file_path):
    while True:
        print("\n" + "="*30)
        print("🎓 Your Online Library")
        print("="*30)
        choice = input("""Choose an option:
1. Add a new book
2. Delete a book
3. View your library
4. Search for a book
5. Exit
Enter your choice (1-5): """)
        
        if choice == "1":
            add_book(library)
            save_library(library, file_path)
        elif choice == "2":
            remove_book(library)
            save_library(library, file_path)
        elif choice == "3":
            show_library(library)
        elif choice == "4":
            search_book(library)
        elif choice == "5":
            save_library(library, file_path)
            print("\n👋 Thanks for using your library—goodbye!")
            break
        else:
            print("\n❌ Invalid choice! Please enter a number between 1 and 5.")

if __name__ == "__main__":
    file_dir = os.path.dirname(__file__)
    biblio_path = os.path.join(file_dir, "bibliotheque.json")
    library = load_library(biblio_path)
    main_menu(library, biblio_path)

Key Improvements Recap

  • Function Encapsulation: Every task has its own dedicated function—no more messy, repeated code
  • Error Prevention: Handles missing files, non-existent books, and invalid user input gracefully
  • Readability: Cleaned up prompts, formatted JSON for humans, and made the UI display easy to scan
  • User Experience: Added friendly feedback messages and small UI tweaks to make the app feel polished

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 09:27:39