👉 项目官网:https://www.python-office.com/ 👈
大家好,这里是程序员晚枫,正在all in AI编程实战 。
今天我们做一个综合实战——通讯录管理系统 !
1、功能需求 我们要做一个通讯录,功能包括:
➕ 添加联系人 🔍 搜索联系人 ✏️ 修改联系人 ❌ 删除联系人 📋 显示所有联系人 💾 数据持久化保存 2、创建数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 import sqlite3import jsonfrom datetime import datetimeclass AddressBook : def __init__ (self, db_path='contacts.db' ): self.db_path = db_path self.conn = sqlite3.connect(db_path) self.cursor = self.conn.cursor() self.create_table() def create_table (self ): """创建联系人表""" self.cursor.execute(''' CREATE TABLE IF NOT EXISTS contacts ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, phone TEXT, email TEXT, company TEXT, address TEXT, remark TEXT, created_at TEXT, updated_at TEXT ) ''' ) self.conn.commit()
3、添加联系人 1 2 3 4 5 6 7 8 9 10 11 def add (self, name, phone='' , email='' , company='' , address='' , remark='' ): """添加联系人""" now = datetime.now().strftime('%Y-%m-%d %H:%M:%S' ) self.cursor.execute(''' INSERT INTO contacts (name, phone, email, company, address, remark, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''' , (name, phone, email, company, address, remark, now, now)) self.conn.commit() print (f'✅ 联系人 {name} 已添加!' )
4、查询联系人 1 2 3 4 5 6 7 8 9 10 11 12 13 def search (self, keyword ): """搜索联系人""" self.cursor.execute(''' SELECT * FROM contacts WHERE name LIKE ? OR phone LIKE ? OR email LIKE ? OR company LIKE ? ''' , (f'%{keyword} %' , f'%{keyword} %' , f'%{keyword} %' , f'%{keyword} %' )) return self.cursor.fetchall() def list_all (self ): """列出所有联系人""" self.cursor.execute('SELECT * FROM contacts ORDER BY name' ) return self.cursor.fetchall()
5、更新和删除 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 def update (self, contact_id, **kwargs ): """更新联系人""" now = datetime.now().strftime('%Y-%m-%d %H:%M:%S' ) fields = [] values = [] for key, value in kwargs.items(): if key != 'id' : fields.append(f'{key} = ?' ) values.append(value) if fields: fields.append('updated_at = ?' ) values.append(now) values.append(contact_id) self.cursor.execute(f''' UPDATE contacts SET {', ' .join(fields)} WHERE id = ? ''' , values) self.conn.commit() print (f'✅ 联系人 ID:{contact_id} 已更新!' ) def delete (self, contact_id ): """删除联系人""" self.cursor.execute('DELETE FROM contacts WHERE id = ?' , (contact_id,)) self.conn.commit() print (f'🗑️ 联系人 ID:{contact_id} 已删除!' )
6、导出功能 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 def export_to_excel (self, filename ): """导出到Excel""" rows = self.list_all() if rows: data = [['ID' , '姓名' , '电话' , '邮箱' , '公司' , '地址' , '备注' , '创建时间' , '更新时间' ]] data.extend(rows) import office office.excel.write(path=filename, data=data) print (f'📊 已导出到 {filename} ' ) def export_to_json (self, filename ): """导出到JSON""" rows = self.list_all() contacts = [] for row in rows: contacts.append({ 'id' : row[0 ], 'name' : row[1 ], 'phone' : row[2 ], 'email' : row[3 ], 'company' : row[4 ], 'address' : row[5 ], 'remark' : row[6 ] }) with open (filename, 'w' , encoding='utf-8' ) as f: json.dump(contacts, f, ensure_ascii=False , indent=4 ) print (f'📋 已导出到 {filename} ' )
7、菜单界面 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 def run (self ): """运行主程序""" while True : print (''' ╔══════════════════════════════════════╗ ║ 📇 通讯录管理系统 v1.0 ║ ╠══════════════════════════════════════╣ ║ 1. 添加联系人 ║ ║ 2. 搜索联系人 ║ ║ 3. 修改联系人 ║ ║ 4. 删除联系人 ║ ║ 5. 列出所有联系人 ║ ║ 6. 导出到Excel ║ ║ 7. 导出到JSON ║ ║ 0. 退出系统 ║ ╚══════════════════════════════════════╝ ''' ) choice = input ('请选择功能:' ) if choice == '1' : name = input ('姓名:' ) phone = input ('电话:' ) email = input ('邮箱:' ) company = input ('公司:' ) self.add(name, phone, email, company) elif choice == '2' : keyword = input ('搜索关键词:' ) results = self.search(keyword) for r in results: print (f'{r[0 ]} . {r[1 ]} - {r[2 ]} ' ) elif choice == '3' : cid = int (input ('联系人ID:' )) phone = input ('新电话(直接回车跳过):' ) if phone: self.update(cid, phone=phone) elif choice == '4' : cid = int (input ('联系人ID:' )) self.delete(cid) elif choice == '5' : for r in self.list_all(): print (f'{r[0 ]} . {r[1 ]} | {r[2 ]} | {r[3 ]} ' ) elif choice == '6' : self.export_to_excel('通讯录.xlsx' ) elif choice == '7' : self.export_to_json('通讯录.json' ) elif choice == '0' : print ('再见!' ) break input ('\n按回车继续...' )
8、运行程序 1 2 3 if __name__ == '__main__' : book = AddressBook() book.run()
9、总结 今天我们做了一个完整的通讯录管理系统:
✅ 使用 SQLite 数据库存储数据 ✅ 支持增删改查基本操作 ✅ 支持搜索功能 ✅ 可以导出 Excel 和 JSON 你可以继续扩展:
添加生日提醒 添加分组功能 添加导入功能 添加微信发送功能 有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》 就能上手做AI项目。
🎓 AI 编程实战课程 想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!