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

Python读取bookdata.txt文本并按作者/书名/关键词检索的问题

实现思路

你目前的存储格式是每本书对应5行有效信息+1行空行分隔,所以可以先把整个文件内容按块解析成结构化的书籍列表,再根据检索条件匹配即可,具体实现如下:

完整检索功能实现代码
def load_books():
    books = []
    with open("bookdata.txt", "r", encoding="utf-8") as f:
        # 去掉空行和每行首尾空白字符
        lines = [line.strip() for line in f if line.strip()]
    # 每5行对应一本书的完整信息
    for i in range(0, len(lines), 5):
        book = {
            "author": lines[i].split(":", 1)[1].strip(),
            "title": lines[i+1].split(":", 1)[1].strip(),
            "keyword": lines[i+2].split(":", 1)[1].strip(),
            "publisher": lines[i+3].split(":", 1)[1].strip(),
            "year": lines[i+4].split(":", 1)[1].strip()
        }
        books.append(book)
    return books

def print_book(book):
    print(f"作者:{book['author']}")
    print(f"书名:{book['title']}")
    print(f"关键词:{book['keyword']}")
    print(f"出版社:{book['publisher']}")
    print(f"出版年份:{book['year']}")
    print("-"*30)

# 原有菜单逻辑
print("************** 检索方式 **************")
print("\t[1] 按作者检索")
print("\t[2] 按书名检索")
print("\t[3] 按关键词检索")
print("\t[4] 返回")
print("***************************************")
    
searchby = input("请输入检索选项: ")
books = load_books()
if not books:
    print("暂无存储的书籍信息")
elif searchby == "1":
    target = input("请输入要检索的作者名: ")
    match_books = [b for b in books if target in b["author"]]
    if match_books:
        print(f"找到{len(match_books)}本匹配的书籍:")
        for b in match_books:
            print_book(b)
    else:
        print("未找到匹配的书籍")
elif searchby == "2":
    target = input("请输入要检索的书名: ")
    match_books = [b for b in books if target in b["title"]]
    if match_books:
        print(f"找到{len(match_books)}本匹配的书籍:")
        for b in match_books:
            print_book(b)
    else:
        print("未找到匹配的书籍")
elif searchby == "3":
    target = input("请输入要检索的关键词: ")
    match_books = [b for b in books if target in b["keyword"]]
    if match_books:
        print(f"找到{len(match_books)}本匹配的书籍:")
        for b in match_books:
            print_book(b)
    else:
        print("未找到匹配的书籍")
elif searchby == "4":
    # 此处补充返回上一级逻辑即可
    pass
补充优化建议
  • 代码中用with open语法读写文件,不需要手动调用close方法,会自动处理文件关闭,避免资源泄漏
  • 当前匹配逻辑为模糊匹配,只要检索内容包含在对应字段中就算匹配,如果需要精确匹配,把判断条件里的in改成==即可
  • 原有写入文件的代码也建议替换为with open写法,更稳定可靠:
with open("bookdata.txt","a", encoding="utf-8") as bookdata:
    Author = input("作者名: ")
    title = input("书名: ")
    keyword = input("书籍关键词: ")
    publisher = input("出版社: ")
    year = input("出版年份: ")

    bookdata.write("Author's Name:    " + Author + "\n")
    bookdata.write("Book Title:       " + title + "\n")
    bookdata.write("Keyword:          " + keyword + "\n")
    bookdata.write("Publisher:        " + publisher + "\n")
    bookdata.write("Year Published:   " + year + "\n\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:48:04