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

如何通过用户输入筛选CSV文件中指定作者的书籍信息

实现作者书籍查询功能的完整方案

Got it, let's fix this up and add the author lookup feature you need! First, we'll optimize your existing CSV writing code for efficiency, then build the query functionality step by step.

优化后的完整代码

import csv

# 1. 录入并存储书籍记录
amount = int(input("How many records would you like to store: "))

with open("Books.csv", "w", newline="") as file:
    writer = csv.writer(file)
    # 把第一个表头改成更清晰的"ID",避免歧义
    writer.writerow(["ID", "Book", "Author", "Year released"])  

    for count in range(1, amount + 1):
        book = input("Enter a book: ")
        author = input("Enter its Author: ")  # 修正拼写it's -> its
        year = input("Enter the year it released: ")
        writer.writerow([count, book, author, year])

# 2. 实现作者书籍查询功能
def get_books_by_author():
    author_name = input("Enter the author's name to find their books: ").strip()
    found_books = []

    with open("Books.csv", "r") as file:
        # 使用DictReader可以通过表头直接访问列数据,代码更直观
        reader = csv.DictReader(file)  
        for row in reader:
            # 转小写+去空格,避免大小写/空格导致的匹配失败
            if row["Author"].strip().lower() == author_name.lower():
                found_books.append(row)

    if found_books:
        print(f"\nBooks by {author_name}:")
        for idx, book in enumerate(found_books, 1):
            print(f"{idx}. {book['Book']} (Released in {book['Year released']})")
    else:
        print(f"No books found for author '{author_name}'.")

# 触发查询功能
get_books_by_author()

关键改进说明

  • 优化写入逻辑:把循环写入放到同一个with块里,避免重复打开/关闭文件,提升效率同时减少资源消耗。
  • 使用csv.DictReader:读取CSV时以字典形式访问列,不用记索引位置,代码可读性大幅提升。
  • 不区分大小写的查询:对输入的作者名和CSV中的作者名统一处理(转小写+去空格),避免用户输入"J.K. Rowling"和CSV里的"j.k. rowling"匹配失败的情况。
  • 友好的输出格式:找到书籍时清晰列出书名和出版年份,未找到时给出明确提示,提升用户体验。

运行流程

  1. 程序先引导你输入要存储的书籍数量,然后依次录入每本书的名称、作者、出版年份。
  2. 录入完成后,自动进入查询环节,提示你输入要查询的作者名字。
  3. 程序会输出该作者的所有书籍信息,或者提示没有找到对应记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:53:04