什么废话都不说,上代码!
import json
class ContactBook:
def __init__(self, filename='contacts.json'):
self.contacts = {}
self.filename = filename
self.load_contacts()
def add_contact(self, name, phones, emails, tags=None):
if tags is None:
tags = []
if name not in self.contacts:
self.contacts[name] = {
'phones': phones if isinstance(phones, list) else [phones],
'emails': emails if isinstance(emails, list) else [emails],
'tags': tags
}
print(f"Contact added: {name} - Phones: {phones}, Emails: {emails}, Tags: {tags}")
else:
print("Contact already exists.")
def find_contact(self, name):
if name in self.contacts:
contact_info = self.contacts[name]
return (f"{name} - Phones: {', '.join(contact_info['phones'])}, "
f"Emails: {', '.join(contact_info['emails'])}, Tags: {', '.join(contact_info['tags'])}")
else:
return "Contact not found."
def update_contact(self, name, new_phones=None, new_emails=None, new_tags=None):
if name in self.contacts:
if new_phones:
self.contacts[name]['phones'] = new_phones if isinstance(new_phones, list) else [new_phones]
if new_emails:
self.contacts[name]['emails'] = new_emails if isinstance(new_emails, list) else [new_emails]
if new_tags is not None:
self.contacts[name]['tags'] = new_tags
print(f"Contact updated: {name} - Phones: {', '.join(self.contacts[name]['phones'])}, "
f"Emails: {', '.join(self.contacts[name]['emails'])}, Tags: {', '.join(self.contacts[name]['tags'])}")
else:
print("Contact not found to update.")
def remove_contact(self, name):
if name in self.contacts:
del self.contacts[name]
print(f"{name} has been removed.")
else:
print("Contact not found to remove.")
def save_contacts(self):
with open(self.filename, 'w') as file:
json.dump(self.contacts, file, ensure_ascii=False, indent=4)
print("Contacts saved to file.")
def load_contacts(self):
try:
with open(self.filename, 'r') as file:
self.contacts = json.load(file)
print("Contacts loaded from file.")
except FileNotFoundError:
print("No existing contact file found, starting fresh.")
except json.JSONDecodeError:
print("Error decoding the contact file, starting with an empty contact book.")
def main():
my_contacts = ContactBook()
while True:
print("\nContact Book Operations:")
print("1 - Add Contact")
print("2 - Find Contact")
print("3 - Update Contact")
print("4 - Remove Contact")
print("5 - Save Contacts to File")
print("6 - Exit")
choice = input("Choose an operation (1-6): ")
if choice == '1':
name = input("Enter the contact name: ")
phones = input("Enter the phone numbers separated by commas: ").split(',')
emails = input("Enter the email addresses separated by commas: ").split(',')
tags = input("Enter tags separated by commas (optional): ").split(',') if input("Do you want to add tags? (yes/no): ").lower() == 'yes' else []
my_contacts.add_contact(name, phones, emails, tags)
elif choice == '2':
name = input("Enter the contact name to find: ")
print(my_contacts.find_contact(name))
elif choice == '3':
name = input("Enter the contact name to update: ")
new_phones = input("Optionally, enter the new phone numbers separated by commas (leave blank if no change): ").split(',')
new_emails = input("Optionally, enter the new email addresses separated by commas (leave blank if no change): ").split(',')
new_tags = input("Enter new tags separated by commas (leave blank if no change): ").split(',') if input("Do you want to update tags? (yes/no): ").lower() == 'yes' else None
my_contacts.update_contact(name, new_phones if new_phones[0] else None, new_emails if new_emails[0] else None, new_tags)
elif choice == '4':
name = input("Enter the contact name to remove: ")
print(my_contacts.remove_contact(name))
elif choice == '5':
my_contacts.save_contacts()
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid option, please choose a valid number (1-6).")
if __name__ == "__main__":
main()
留下评论