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
廣告