十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
可以将数据存储在列表里
创新互联公司2013年成立,先为中方等服务建站,中方等地企业,进行企业商务咨询服务。为中方企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
然后再将列表保存到文件里
通过对列表的操作动态更改存储在文件里的内容
如果有文件的话程序启动时从文件里加载数据保存到列表即可
如果代码不想自己写的话
我可以有偿代劳
python手机通讯录封装方法:
1、用户输入1时,执行增加姓名和手机号码的操作。
2、选择字典,转换为元组放在列表里保存break即可。
要求提的不是很明确,按照最简单的功能来做了。
只记录姓名和电话号码,没有做号码检验。也没有做保存功能。
import sys
last_id = 0
class Person:
def __init__(self, name, phone):
self.name = name
self.phone = phone
global last_id
last_id += 1
self.id = last_id
def match(self, filter):
return filter in self.name or filter in self.phone
class AddressBook:
def __init__(self):
self.people = []
def new_person(self, name, phone=''):
self.people.append(Person(name, phone))
def find_person(self, id):
for person in self.people:
if str(id) == str(person.id):
return person
return None
def modify_person(self, id, name, phone):
person = self.find_person(id)
if person:
person.name = name
person.phone = phone
else:
print "person:", id, " not found"
def delete_person(self, id):
person = self.find_person(id)
if person:
self.people.remove(person)
def search(self, filter):
return [person for person in self.people if person.match(filter)]
class Menu:
def __init__(self):
self.address_book = AddressBook()
self.choices = {
"1": self.show_people,
"2": self.add_person,
"3": self.remove_person,
"4": self.modify_person,
"5": self.search_person,
"6": self.quit
}
def display_menu(self):
print("""
Address Book Menu
1. Show all People
2. Add Person
3. Remove Person
4. Modify Person
5. Search Person
6. Quit
""")
def run(self):
while True:
self.display_menu()
choice = raw_input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
def show_people(self, people=None):
if not people:
people = self.address_book.people
for person in people:
print("{0}: {1} {2}".format(person.id, person.name, person.phone))
def search_person(self):
filter = raw_input("search for: ")
people = self.address_book.search(filter)
self.show_people(people)
def add_person(self):
name = raw_input("Enter a name: ")
phone = raw_input("Enter his/her phone number: ")
self.address_book.new_person(name, phone)
print("{0} has been added.".format(name))
def remove_person(self):
id = raw_input("Enter his/her id: ")
if id:
self.address_book.delete_person(id)
def modify_person(self):
id = raw_input("Enter a person id: ")
name = raw_input("Enter his/her name: ")
phone = raw_input("Enter his/her phone: ")
self.address_book.modify_person(id, name, phone)
def quit(self):
print("Thank you for using your address book today.")
sys.exit(0)
Menu().run()