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

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

迷你在线图书馆代码优化与函数封装建议

Hey Hugo, awesome work getting this functional mini library up and running using JSON—starting with simpler storage to nail down file operations is a perfect call for a beginner! Let's walk through how to refine your code, wrap logic into functions, and smooth out some rough edges.

一、函数封装:把重复逻辑模块化

Right now, your code has repeated steps (like writing to the JSON file) scattered across each option. Wrapping these into functions will make your code cleaner, easier to debug, and reusable. Here's how to split it up:

1. 数据读写函数

These handle the repetitive JSON file operations so you don't have to copy-paste the same open() blocks every time:

def load_library(file_path):
    """从JSON文件加载图书馆数据"""
    if not os.path.exists(file_path):
        # 如果文件不存在,返回空列表
        return []
    with open(file_path, 'r') as f:
        return json.load(f)

def save_library(library_data, file_path):
    """将图书馆数据保存到JSON文件"""
    with open(file_path, "w") as f:
        json.dump(library_data, f, indent=4)  # indent让JSON更易读

2. 功能模块函数

Turn each user action into its own function—this keeps your main loop clean and focused on user input:

def add_book(library):
    """添加书籍到图书馆"""
    book_title = input("Enter the title of your new book: ")
    book_author = input("Enter the author's name: ")
    new_book = {"book": book_title, "author": book_author}
    library.append(new_book)
    print(f"Added '{book_title}' by {book_author} to your library!")

def delete_book(library):
    """从图书馆删除指定书籍"""
    author_name = input("Enter the author's name: ")
    book_name = input("Enter the title of the book to delete: ")
    book_to_remove = {"book": book_name, "author": author_name}
    try:
        library.remove(book_to_remove)
        print(f"Removed '{book_name}' by {author_name} from your library!")
    except ValueError:
        print("That book isn't in your library—double-check the title and author!")

def view_library(library):
    """用Tkinter显示图书馆书籍"""
    window = tk.Tk()
    window.title("My Online Library")
    # 把书籍列表转成更友好的字符串格式
    library_text = "\n".join([f"- {book['book']} by {book['author']}" for book in library])
    if not library_text:
        library_text = "Your library is empty!"
    label = tk.Label(window, text=library_text, justify="left", padx=10, pady=10)
    bouton = tk.Button(window, text="Quit", fg="red", command=window.destroy)
    label.pack()
    bouton.pack()
    window.mainloop()  # 启动Tkinter主循环(之前你的代码缺这个,窗口会一闪而过)

def search_book(library):
    """搜索图书馆中是否存在指定书籍"""
    author_searched = input("Enter the author's name: ")
    book_searched = input("Enter the title of the book you're looking for: ")
    target_book = {"book": book_searched, "author": author_searched}
    if target_book in library:
        print(f"You have '{book_searched}' by {author_searched} in your library!")
    else:
        print(f"You don't have '{book_searched}' by {author_searched} yet.")

二、语法与细节优化

  • 用elif替代多个独立if: 你的原代码每次都会检查所有if条件,哪怕已经匹配了一个选项。用elif会更高效:
    # 替换原有的多个if为:
    if choice == "1":
        add_book(library)
        save_library(library, biblio_path)
    elif choice == "2":
        delete_book(library)
        save_library(library, biblio_path)
    elif choice == "3":
        view_library(library)
    elif choice == "4":
        search_book(library)
    else:
        print("Invalid choice—please enter 1, 2, 3, or 4!")
    
  • 修复拼写错误: tittle → title(输入提示里的拼写)
  • Tkinter添加mainloop(): 原代码里的窗口会一闪而过,加上window.mainloop()才能让窗口保持打开
  • 美化JSON输出: 保存时加indent=4,让生成的JSON文件更易读
  • 异常处理: 删除书籍时加try-except,避免因为书籍不存在导致程序崩溃

三、重构后的完整代码

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_data, file_path):
    with open(file_path, "w") as f:
        json.dump(library_data, f, indent=4)

# 功能模块函数
def add_book(library):
    book_title = input("Enter the title of your new book: ")
    book_author = input("Enter the author's name: ")
    new_book = {"book": book_title, "author": book_author}
    library.append(new_book)
    print(f"Added '{book_title}' by {book_author} to your library!")

def delete_book(library):
    author_name = input("Enter the author's name: ")
    book_name = input("Enter the title of the book to delete: ")
    book_to_remove = {"book": book_name, "author": author_name}
    try:
        library.remove(book_to_remove)
        print(f"Removed '{book_name}' by {author_name} from your library!")
    except ValueError:
        print("That book isn't in your library—double-check the title and author!")

def view_library(library):
    window = tk.Tk()
    window.title("My Online Library")
    library_text = "\n".join([f"- {book['book']} by {book['author']}" for book in library])
    if not library_text:
        library_text = "Your library is empty!"
    label = tk.Label(window, text=library_text, justify="left", padx=10, pady=10)
    bouton = tk.Button(window, text="Quit", fg="red", command=window.destroy)
    label.pack()
    bouton.pack()
    window.mainloop()

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

# 主程序逻辑
if __name__ == "__main__":
    file = os.path.dirname(__file__)
    biblio_path = os.path.join(file, "bibliotheque.json")
    library = load_library(biblio_path)

    while True:
        choice = input("""Welcome to your online library. 
Would you like to (1) add a new book, (2) delete a book, (3) view your library, or (4) search for a book? 
Enter your choice (1-4): """)
        if choice == "1":
            add_book(library)
            save_library(library, biblio_path)
        elif choice == "2":
            delete_book(library)
            save_library(library, biblio_path)
        elif choice == "3":
            view_library(library)
        elif choice == "4":
            search_book(library)
        else:
            print("Oops, that's not a valid option. Please enter 1, 2, 3, or 4!")

额外小建议

  • 可以考虑添加退出选项(比如输入5退出循环),不然用户只能强行终止程序
  • 后续如果想迁移到SQL,你可以把load_library和save_library替换成数据库读写逻辑,其他功能函数几乎不用改——这就是模块化的好处!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 06:40:07