之前简单介绍了有关Python的面向对象中的类,这次就围绕"类"和json格式来做一个简单的代码程序,并且在后面还附带了数据。
import json
import re
import time
class BookManager:
def __init__(self):
self.books = {} # 使用字典存储书籍信息,book_id
# 导入书籍信息
def load_books(self, filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
self.books = json.load(file)
if not self.books:
return # 如果字典为空,返回
except (json.JSONDecodeError, FileNotFoundError):
return # 如果文件为空,或不存在,或无法解析,直接返回
def save_books(self):
filename = r'books.json'
with open(filename, 'w', encoding='utf-8') as file:
# 没有书籍信息就不保存,并直接退出
if self.books == {}:
exit()
# 保存书籍信息,并退出
json.dump(obj=self.books, fp=file, indent=4, ensure_ascii=False)
exit()
def register_book(self):
print("请输入书籍信息:")
book_id = input("书籍ID: ")
isbn = input("ISBN: ")
title = input("书名: ")
author = input("作者: ")
genre = input("类型: ")
# 检验书籍的有效性
if self.validate_isbn(isbn) and \
self.validate_book_id(book_id) and \
book_id not in self.books.keys():
self.books[book_id] = {
'title': title,
'author': author,
'book_id': book_id,
'genre': genre,
'isbn': isbn
}
else:
print("书籍ID和ISBN无效或已存在。")
def delete_book_by_id(self):
book_id = input("输入要删除的书籍ID: ")
if book_id in self.books.keys():
del self.books[book_id]
print("书籍已删除。")
else:
print("找不到该书籍。")
def modify_book(self):
book_id = input("输入要修改的书籍ID: ")
if book_id in self.books.keys():
print("输入新的书籍信息(如果不想修改某项,请直接按回车键):")
new_ISBN = input("ISBN: ")
new_title = input("书名: ")
new_author = input("作者: ")
new_genre = input("类型: ")
# 如果输入不为空,则更新相应的信息
if new_ISBN:
self.books[book_id]['ISBN'] = new_ISBN
if new_title:
self.books[book_id]['title'] = new_title
if new_author:
self.books[book_id]['author'] = new_author
if new_genre:
self.books[book_id]['genre'] = new_genre
print("书籍信息已更新。")
else:
print("找不到该书籍。")
def display_books(self):
# 没有书籍信息,就返回
if not self.books:
print("暂无书籍信息。")
return
# 遍历所有书籍信息
print("所有书籍如下: ")
for index, book in enumerate(self.books.values(), start=1):
print(index, book, sep='、', end='\n')
def find_book_by_id(self):
book_id = input("输入书籍ID: ")
if book_id in self.books.keys():
print(self.books[book_id])
else:
print("找不到该ID的书籍信息。")
def find_book_by_title(self):
title = input("输入书名: ")
found = False
for book in self.books.values():
# 检查输入的书名是否为书籍标题的一部分
if title in book['title']:
print(f"{book}")
found = True
if not found:
print("没有找到该书名的书籍。")
def find_book_by_genre(self):
genre = input("输入书籍类型: ")
found = False
index = 1
for book in self.books.values():
# 检查输入的书名是否为书籍标题的一部分
if genre in book['genre']:
print(f"{index}、{book}")
index = index + 1
found = True
if not found:
print("没有该类型书籍。")
# 检验书籍的ISBN位数是否合理——13位数字
def validate_isbn(self, isbn):
pattern = r'^\d{13}$'
return re.match(pattern, isbn) is not None
# 检验书籍的ID是否符合——数字
def validate_book_id(self, id):
pattern = r'^\d+$'
return re.match(pattern, id) is not None
def main():
manager = BookManager()
manager.load_books('books.json')
# 以索引为关键字,创建一个字典来存储类方法
options = {
'1': manager.register_book,
'2': manager.delete_book_by_id,
'3': manager.modify_book,
'4': manager.display_books,
'5': manager.find_book_by_id,
'6': manager.find_book_by_title,
'7': manager.find_book_by_genre,
'8': manager.save_books
}
while True:
time.sleep(2)
print("\n主菜单:")
print("1. 登记书籍")
print("2. 删除书籍")
print("3. 修改书籍")
print("4. 显示所有书籍")
print("5. 按ID查找书籍")
print("6. 按书名查找书籍")
print("7. 按类型查找书籍")
print("8. 保存并退出程序")
choice = input("请选择操作: ")
if choice in options.keys():
options[choice]()
else:
print("无效选项,请重新选择。")
if __name__ == '__main__':
main()
{
"1": {
"title": "云边有个小卖部",
"author": "张嘉佳",
"book_id": "1",
"genre": "情感小说",
"isbn": "9787540487645"
},
"2": {
"title": "月亮和六便士",
"author": "威廉·萨默塞特·毛姆",
"book_id": "2",
"genre": "文学经典",
"isbn": "9787530216787"
},
"3": {
"title": "解忧杂货店",
"author": "东野圭吾",
"book_id": "3",
"genre": "悬疑小说",
"isbn": "9787544270878"
},
"4": {
"title": "挪威的森林",
"author": "村上春树",
"book_id": "4",
"genre": "现代文学",
"isbn": "9787544731703"
},
"5": {
"title": "百年孤独",
"author": "加西亚·马尔克斯",
"book_id": "5",
"genre": "魔幻现实主义",
"isbn": "9787544268103"
},
"6": {
"title": "活着",
"author": "余华",
"book_id": "6",
"genre": "现实主义",
"isbn": "9787506365437"
},
"7": {
"title": "小王子",
"author": "安托万·德·圣埃克苏佩里",
"book_id": "7",
"genre": "童话",
"isbn": "9787020042494"
},
"8": {
"title": "围城",
"author": "钱钟书",
"book_id": "8",
"genre": "现代文学",
"isbn": "9787020024759"
},
"9": {
"title": "追风筝的人",
"author": "卡勒德·胡赛尼",
"book_id": "9",
"genre": "现代文学",
"isbn": "9787208061644"
},
"10": {
"title": "苏菲的世界",
"author": "乔斯坦·贾德",
"book_id": "10",
"genre": "哲学",
"isbn": "9787532739824"
},
"11": {
"title": "瓦尔登湖",
"author": "亨利·大卫·梭罗",
"book_id": "11",
"genre": "自然写作",
"isbn": "9787544261098"
},
"12": {
"title": "简爱",
"author": "夏洛蒂·勃朗特",
"book_id": "12",
"genre": "古典文学",
"isbn": "9787544242516"
},
"13": {
"title": "1984",
"author": "乔治·奥威尔",
"book_id": "13",
"genre": "反乌托邦",
"isbn": "9787208061643"
},
"14": {
"title": "飘",
"author": "玛格丽特·米切尔",
"book_id": "14",
"genre": "历史小说",
"isbn": "9787532745115"
},
"15": {
"title": "动物农场",
"author": "乔治·奥威尔",
"book_id": "15",
"genre": "政治讽刺",
"isbn": "9787532739138"
},
"16": {
"title": "荆棘鸟",
"author": "科琳·麦卡洛",
"book_id": "16",
"genre": "家庭史诗",
"isbn": "9787208115279"
},
"17": {
"title": "哈利波特与魔法石",
"author": "J.K. 罗琳",
"book_id": "17",
"genre": "奇幻",
"isbn": "9787020033430"
},
"18": {
"title": "了不起的盖茨比",
"author": "弗朗西斯·斯科特·菲茨杰拉德",
"book_id": "18",
"genre": "美国小说",
"isbn": "9787532737974"
},
"19": {
"title": "不可抗力",
"author": "玛丽安娜·海拉",
"book_id": "19",
"genre": "现代小说",
"isbn": "9787544291179"
},
"20": {
"title": "我们仨",
"author": "杨绛",
"book_id": "20",
"genre": "回忆录",
"isbn": "9787530219214"
},
"21": {
"title": "天才在左 疯子在右",
"author": "高铭",
"book_id": "21",
"genre": "心理学",
"isbn": "9787508657421"
},
"22": {
"title": "我与地坛",
"author": "史铁生",
"book_id": "22",
"genre": "散文",
"isbn": "9787530216770"
},
"23": {
"title": "地球往事",
"author": "刘慈欣",
"book_id": "23",
"genre": "科幻",
"isbn": "9787536692930"
},
"24": {
"title": "平凡的世界",
"author": "路遥",
"book_id": "24",
"genre": "现实主义",
"isbn": "9787020016402"
},
"25": {
"title": "无人生还",
"author": "阿加莎·克里斯蒂",
"book_id": "25",
"genre": "悬疑",
"isbn": "9787208060943"
}
}
基本功能
- 登记书籍:
- 用户可以输入书籍的ID、ISBN、书名、作者和类型来登记一本新书。
- 程序会验证书籍ID和ISBN的有效性,避免重复登记。
- 删除书籍:
- 通过输入书籍ID,用户可以删除已登记的书籍信息。
- 修改书籍:
- 用户可以输入书籍ID,然后修改书籍的ISBN、书名、作者或类型。
- 只需输入需要修改的项,不修改的项可以直接按回车键跳过。
查询功能
- 显示所有书籍:
- 列出所有已登记的书籍信息,便于用户浏览。
- 按ID查找书籍:
- 通过输入书籍ID,用户可以查找并显示特定书籍的信息。
- 按书名查找书籍:
- 用户可以输入书名的一部分或全部,程序会查找并显示包含该书名的所有书籍信息。
- 按类型查找书籍:
- 通过输入书籍类型,用户可以查找并显示所有属于该类型的书籍。
其他功能
- 保存并退出程序:
- 程序会将所有书籍信息保存到名为
books.json
的文件中,并退出程序。 - 如果没有书籍信息,将不会保存文件。
- 程序会将所有书籍信息保存到名为
程序结构
BookManager
类负责所有书籍管理的核心功能,包括导入、导出书籍信息,登记、删除、修改和查找书籍。main
函数提供一个简单的命令行菜单,用户可以通过选择不同的选项来执行相应的操作。