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
| import json import os
class ContactManager: def __init__(self, filename="contacts.json"): self.filename = filename self.contacts = self.load_contacts() def load_contacts(self): if os.path.exists(self.filename): with open(self.filename, "r") as f: return json.load(f) return {} def save_contacts(self): with open(self.filename, "w") as f: json.dump(self.contacts, f, indent=2, ensure_ascii=False) def add_contact(self, name, phone, email): if name in self.contacts: print(f"联系人 {name} 已存在") return self.contacts[name] = {"phone": phone, "email": email} self.save_contacts() print(f"已添加: {name}") def delete_contact(self, name): if name in self.contacts: del self.contacts[name] self.save_contacts() print(f"已删除: {name}") else: print(f"联系人 {name} 不存在") def search_contact(self, name): if name in self.contacts: info = self.contacts[name] print(f"姓名: {name}") print(f"电话: {info['phone']}") print(f"邮箱: {info['email']}") else: print(f"未找到: {name}") def show_all(self): if not self.contacts: print("通讯录为空") return for name, info in self.contacts.items(): print(f"{name}: {info['phone']}, {info['email']}")
manager = ContactManager() manager.add_contact("Alice", "13800138000", "alice@example.com") manager.add_contact("Bob", "13900139000", "bob@example.com") manager.show_all() manager.search_contact("Alice")
|