Python通讯录应用程序



Python通讯录应用程序是一个简单但有效的工具,用于管理个人联系人。通过此应用程序,用户可以添加、查看、删除和搜索联系人,同时确保电话号码得到正确验证。通讯录将所有信息存储在JSON文件中,以便轻松地在会话之间保留数据。

通讯录应用程序的工作流程

通讯录应用程序旨在使用Python管理您的联系人。以下是它的工作原理:

  • 加载联系人 应用程序启动时,会检查是否存在contact.json文件。如果找到,则将保存的联系人加载到程序中。
  • 添加联系人 您可以通过提供姓名、电话号码和电子邮件来添加新的联系人。电话号码将被检查以确保它是数字,并且不超过10位。
  • 查看联系人 要查看所有联系人,只需选择查看选项。应用程序将以用户友好的格式显示每个联系人的详细信息。
  • 删除联系人 如果您需要删除联系人,只需输入联系人的姓名,如果存在,应用程序将将其从列表中删除。
  • 搜索联系人 您可以按姓名快速找到联系人。如果联系人存在于列表中,应用程序将显示详细信息。
  • 保存联系人 当您退出应用程序时,您的更改将保存到contacts.json中,因此您不会丢失任何信息。

实现通讯录应用程序的Python代码

import json
import os
import re

# File to store contacts
CONTACTS_FILE = 'contacts.json'

def load_contacts():
   """Load contacts from the JSON file."""
   if os.path.exists(CONTACTS_FILE):
      with open(CONTACTS_FILE, 'r') as file:
         return json.load(file)
   return {}

def save_contacts(contacts):
   """Save contacts to the JSON file."""
   with open(CONTACTS_FILE, 'w') as file:
      json.dump(contacts, file, indent=4)

def add_contact(contacts):
   """Add a new contact with phone number validation."""
   name = input("Enter contact name: ").strip()
   phone = input("Enter contact phone number: ").strip()

   # Validate phone number length
   if len(phone) > 10:
      print("Phone number should not exceed 10 digits.")
      return

   # Optional: Further validate phone number format (e.g., only digits)
   if not re.match(r'^\d+$', phone):
      print("Phone number should contain only digits.")
      return

   email = input("Enter contact email: ").strip()
   contacts[name] = {'phone': phone, 'email': email}
   print(f"Contact '{name}' added.")

def view_contacts(contacts):
   """View all contacts."""
   if not contacts:
      print("No contacts found.")
      return
   for name, info in contacts.items():
      print(f"Name: {name}")
      print(f"Phone: {info['phone']}")
      print(f"Email: {info['email']}\n")

def delete_contact(contacts):
   """Delete a contact."""
   name = input("Enter contact name to delete: ").strip()
   if name in contacts:
      del contacts[name]
      print(f"Contact '{name}' deleted.")
   else:
      print("Contact not found.")

def search_contact(contacts):
   """Search for a contact."""
   name = input("Enter contact name to search: ").strip()
   if name in contacts:
      info = contacts[name]
      print(f"Name: {name}")
      print(f"Phone: {info['phone']}")
      print(f"Email: {info['email']}")
   else:
      print("Contact not found.")

def main():
   contacts = load_contacts()
   while True:
      print("\nContact Book")
      print("1. Add Contact")
      print("2. View Contacts")
      print("3. Delete Contact")
      print("4. Search Contact")
      print("5. Exit")
      choice = input("Enter your choice: ").strip()
        
      if choice == '1':
         add_contact(contacts)
      elif choice == '2':
         view_contacts(contacts)
      elif choice == '3':
         delete_contact(contacts)
      elif choice == '4':
         search_contact(contacts)
      elif choice == '5':
         save_contacts(contacts)
         print("Contacts saved. Exiting...")
         break
      else:
         print("Invalid choice. Please try again.")

if __name__ == "__main__":
   main()

输出

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 1
Enter contact name: Sudhir
Enter contact phone number: 1234567890
Enter contact email: temp1@gmail.com
Contact 'Sudhir' added.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 2 1
Enter contact name: Krishna
Enter contact phone number: 1118882340
Enter contact email: kkk@gmail, .com
Contact 'Krishna' added.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 2
Name: Sudhir
Phone: 1234567890
Email: temp1@gmail.com

Name: Krishna
Phone: 1118882340
Email: kkk@gmail.com


Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 5
Contacts saved. Exiting...

这是正常的输出,但是如果您在电话号码中输入超过10个数字,它将显示:

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 1
Enter contact name: Sudhir
Enter contact phone number: 777   123456789012
Phone number should not exceed 10 digits.

Contact Book
1. Add Contact
2. View Contacts
3. Delete Contact
4. Search Contact
5. Exit
Enter your choice: 5
Contacts saved. Exiting...
python_projects_from_basic_to_advanced.htm
广告
© . All rights reserved.