写完上篇博客记录心情后就接着去弄那个题了。是看了下@图书馆的恶魔 的代码 有了启发。其实是非常简单的题。自己想的太复杂了。写出来还是比较开心的,先记录下初版本,如果以后有所改进再更新,希望路过的大神们多多指点。
import pickle
import sys
filename='chat_book.txt'
book={}
try:
f=open(filename,'rb')
book=pickle.load(f)
f.close()
except EOFError:
pass
#定义一个类用来存储人的信息
class info:
def __init__(self,name,phone):
self.name=name
self.phone=phone
#增加联系人
def add():
name=input('please enter the name:')
if name in book:
is_modify=input('The contacts already exist.Do you want you modify? yes or no:')
if is_modify=='yes':
mod_info=input('please input the phone:')
book[name]=mod_info
print('You successfully modify the information:')
print('The information is:name:{},phone:{}'.format(name, book[name]))
else:
sys.exit()
else:
phone=input('please enter the phone:')
book[name]=phone
print('You successfully add the contacts:')
print('The information is:name:{},phone:{}'.format(name,phone))
#删除联系人
def delete():
name=input('please enter the name you want delete:')
if name in book:
del book[name]
print('You successfully delete the contacts :{}'.format(name))
else:
print('This contacts is not in the chatbook.')
#寻找联系人信息
def research():
name=input('please enter the name:')
if name in book:
print('The contacts {} in the chat_book'.format(name))
print('The information is:name:{},phone:{}'.format(name, book[name]))
else:
print('sorry.This contacts is not in the chat_book.')
while True:
menu = input('''
1.查询
2.添加/修改
3.删除
4.打印通讯表
x.退出
------>''')
if menu == '1':
research()
elif menu == '2':
add()
elif menu == '3':
delete()
elif menu == '4':
for name in book:
print('name:{},phone:{}'.format(name,book[name]))
elif menu == 'x':
sys.exit()
else:
print("Don't have this option,please try again!")
f=open(filename,'wb')
pickle.dump(book,f)
f.close()
print('保存完成!')
sys.exit()