用Python语言生成一个手机通讯录管理系统,其功能包括查询信息,分组,修改
时间: 2024-05-15 07:12:16 浏览: 122
好的,下面是一个简单的 Python 通讯录管理系统代码示例:
```python
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
class ContactBook:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def remove_contact(self, contact):
self.contacts.remove(contact)
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
return contact
def group_contacts(self):
groups = {}
for contact in self.contacts:
if contact.email not in groups:
groups[contact.email] = []
groups[contact.email].append(contact)
return groups
def update_contact(self, contact, name, phone, email):
contact.name = name
contact.phone = phone
contact.email = email
def main():
contacts = ContactBook()
while True:
print("1. Add Contact")
print("2. Remove Contact")
print("3. Search Contact")
print("4. Group Contacts")
print("5. Update Contact")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == "1":
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
contact = Contact(name, phone, email)
contacts.add_contact(contact)
print("Contact added successfully.")
elif choice == "2":
name = input("Enter name: ")
contact = contacts.search_contact(name)
if contact:
contacts.remove_contact(contact)
print("Contact removed successfully.")
else:
print("Contact not found.")
elif choice == "3":
name = input("Enter name: ")
contact = contacts.search_contact(name)
if contact:
print("Name:", contact.name)
print("Phone:", contact.phone)
print("Email:", contact.email)
else:
print("Contact not found.")
elif choice == "4":
groups = contacts.group_contacts()
for email, group in groups.items():
print("Email:", email)
for contact in group:
print("Name:", contact.name)
print("Phone:", contact.phone)
print()
elif choice == "5":
name = input("Enter name: ")
contact = contacts.search_contact(name)
if contact:
new_name = input("Enter new name: ")
new_phone = input("Enter new phone: ")
new_email = input("Enter new email: ")
contacts.update_contact(contact, new_name, new_phone, new_email)
print("Contact updated successfully.")
else:
print("Contact not found.")
elif choice == "6":
break
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
```
这个程序中定义了两个类:`Contact` 和 `ContactBook`。`Contact` 类表示一个联系人,包括姓名、电话和电子邮件。`ContactBook` 类表示整个通讯录,包括一组联系人,以及添加、删除、查询、分组和修改联系人的方法。
在主函数中,使用一个循环显示菜单,根据用户的选择执行相应的操作。用户可以添加、删除、查询、分组和修改联系人,也可以退出程序。
阅读全文