python实现简单的电话本功能

myphonebook2.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
class phonebook(object):
”’这是一个电话簿脚本。
该脚本能够实现
addcontact:添加联系人信息
showcontact:查找姓名显示联系人
savecontacts:存储联系人到 txt 文档(存储格式——姓名:号码/号码)
loadcontacts:从 txt 文档中载入联系人
”’
def __init__(self):
self.contactsdict = {}
def addcontact(self):
while true:
name = raw_input(‘请输入姓名>>>’)
name = name.strip()
# 姓名必须包含有效字符
if name != ”:
break
print ‘***姓名不能为空’
while true:
number = raw_input(‘请输入号码>>>’)
number = re.sub(r’\d’, ”, number)
# 删除号码中的非数字字符
if number != ”:
break
print ‘***号码只能是数字’
cover = true #若联系人已存在,是否覆盖
if self.contactsdict.has_key(name):
print ‘***联系人已存在’
self.showcontact(name)
while true:
control = raw_input(”’
输入 “c”:覆盖原来号码
输入 “n”:保留原来号码并存储新号码
输入 “q” 退出\n>>>”’)
if control.lower() == ‘n’:
cover = false
break
if control.lower() == ‘c’:
break
if control.lower() == ‘q’:
return none
print ‘***输入错误’
if cover:
self.contactsdict[name] = number
else:
if number in self.contactsdict[name]:
print ‘***号码已经存在’
else:
self.contactsdict[name] = self.contactsdict[name] + ‘/’ + number
def showcontact(self, name):
print ‘++++++++++++++++++++++++’
if self.contactsdict.has_key(name):
print ‘【联系人信息】’
print ‘【姓名: %s】’ % name
numberlist = self.contactsdict[name].split(‘/’)
for num in range(len(numberlist)):
print ‘【号码%d: %s】’ % (num+1, numberlist[num])
else:
print ‘【找不到联系人%s】’ % name
print ‘++++++++++++++++++++++++’
def deletenumber(self, name):
if self.contactsdict.has_key(name):
self.showcontact(name)
number = self.contactsdict[name].split(‘/’)
while true:
print ”’
请输入要删除号码的序号
或者输入 “a” 删除该联系人
或者输入 “q” 退出(不删除)
(若联系人号码被全部删除,该联系人也将被删除)”’
control = raw_input(‘>>>’)
if control.lower() == ‘q’:
break
elif control.lower() == ‘a’:
del self.contactsdict[name]
break
elif control.isdigit() and int(control) 0:
print message
def debug(message):
global debug
if debug > 1:
print message
def warn(message):
global debug
if debug > 0:
print message
def error(message):
print message
def help():
print “用法:输入菜单中的命令即可执行相应操作!”
print “可用菜单命令如下:”
showmenu()
def showmenu():
print “+******************操作菜单***********************+”
print “|查看所有联系人(all) | 查找联系人(find) |”
print “|添加联系人(add) | 删除联系人(remove) |”
print “|编辑联系人(edit) | 保存并退出(save) |”
print “|使用帮助(help) | 退出但不保存(quit) |”
print “+_________________________________________________+”
def showerror(info):
print info
def doswitch(op):
if op == “all”:
doall()
elif op == “find”:
dofind()
elif op == “add”:
doadd()
elif op == “remove”:
doremove()
elif op == “edit”:
doedit()
elif op == “save”:
dosave()
elif op == “help”:
help()
elif op == “quit”:
doquit()
else:
showerror(“错误:您输入的命令有误,请重新输入。需要帮助请输入help!”)
def verifyinput(items):
_flag = true
_rphone = re.compile(r’1[0-9]{10}’)
_rqq = re.compile(r'[1-9][0-9]{4,9}’)
if len(items[0]) > 10:
_flag = false
print “姓名太长了!”
if not _rphone.match(items[1]):
_flag = false
print “手机号码格式不正确”
if not _rqq.match(items[2]):
_flag = false
print “qq号码输入有误”
return _flag
def buildaddr(addr):
_addr={}
items=addr.split()
if len(items) < 3: print "您输入的信息太少了" return none if not verifyinput(items): return none _addr['name']=items[0] _addr['phone'] = items[1] _addr['qq'] = items[2] return _addr def addaddr(addr): global _addrs_count,_addrs_dict _addrs_count+=1 _addr=buildaddr(addr) if not _addr: return none _addrs_dict[_addrs_count]=_addr def init(): if not os.path.isfile(addrs_list): return none faddr=open(addrs_list,"r") for line in faddr: if len(line) == 0: continue addaddr(line) faddr.close() def save(): global _addrs_dict faddr=open(addrs_list,"w+") for addr in _addrs_dict.values(): faddr.write("{0}\t{1}\t{2}\n".format(addr['name'],addr['phone'],addr['qq'])) faddr.flush() faddr.close() def doall(): global _addrs_dict if len(_addrs_dict) < 1: print "联系人当中暂无记录!" return none printhead() for key,addr in _addrs_dict.items(): printaddr(key,addr) def dofind(): _flag=false flag1=flag2=flag3=false cond=raw_input("请输入查询信息:>“)
debug(“debug:{0}”.format(cond))
if len(cond) == 0:
return none
if cond.isdigit():
flag1=findbyid(int(cond,10))
flag2=findbyphone(cond)
flag3=findbyqq(cond)
else:
flag1=findbyname(cond)
_flag = flag1 or flag2 or flag3
if not _flag:
print “没有查找到任何联系人!”
def doadd():
line = raw_input(“请依次输入联系人的姓名,手机号码,qq号码>”)
if len(line) == 0:
return none
addaddr(line)
def existsid(_id):
global _addrs_dict
return _addrs_dict.has_key(_id)
# if _id > _addrs_count or _id < 1: # return false # else: # return true def doremove(): flag = true while flag: key=raw_input("请输入要删除的联系人的编号(取消请输入#)") if key == '#': flag = false continue if not existsid(int(key,10)): print "不存在您所输入编号的联系人。请确认" continue print "编号为 {0} 的联系人信息如下:".format(key) printbyid(int(key,10)) yesorno=raw_input("您确定要删除上述联系人吗?(y/n)") if yesorno in "yy": removebyid(int(key,10)) print "删除成功!" yesorno=raw_input("您还需要继续删除联系人吗?(y/n)") if not yesorno in "yy": flag = false def doedit(): flag = true while flag: key=raw_input("请输入要编辑的联系人的编号(取消请输入#)") print "debug:key:{0}".format(key) if key == '#': flag = false continue if not existsid(int(key,10)): print "不存在您所输入编号的联系人。请确认" continue print "编号为 {0} 的联系人信息如下:".format(key) printbyid(int(key,10)) updatebyid(int(key,10)) flag = false def dosave(): save() doquit() def doquit(): global quit_flag quit_flag = true print "正在退出……" # exit(0) def printhead(): print "+-----+----------+---------------+---------------+" print "|编号 | 姓名 | 手机号码 | qq号码 |" print "+-----+----------+---------------+---------------+" def printaddr(key,addr): # print "+-----+----------+---------------+---------------+" print "|{0:^5}|{1:^10}|{2:^15}|{3:^15}|".format(key,addr['name'],addr['phone'],addr['qq']) print "+-----+----------+---------------+---------------+" def printbyid(_id): global _addrs_dict printhead() printaddr(_id,_addrs_dict[_id]) def removebyid(_id): global _addrs_dict _addrs_dict.pop(_id) def updatebyid(_id): global _addrs_dict _addr= _addrs_dict.get(_id) print "请输入该联系人的新信息,相应留空则保留原有信息" name=raw_input("请输入新姓名:>“)
if len(name) > 0:
_addr[‘name’]=name
phone=raw_input(“请输入新手机号码:>”)
if len(phone) > 0:
_addr[‘phone’]=phone
qq=raw_input(“请输入新的qq号码:>”)
if len(qq) > 0 :
_addr[‘qq’]=qq
_addrs_dict[_id]=_addr
print “更新成功!”
print “联系人新的信息如下:”
printbyid(_id)
def findbyid(_id):
if existsid(_id):
printbyid(_id)
return true
else:
return false
def findbyfield(cond,field=’name’):
global _addrs_dict
_flag = false
for key,addr in _addrs_dict.items():
if addr[field].find(cond) != -1:
printaddr(key,addr)
_flag=true
return _flag
def findbyname(name):
return findbyfield(name,’name’)
def findbyphone(phone):
return findbyfield(phone,’phone’)
def findbyqq(qq):
return findbyfield(qq,’qq’)
def main():
init()
showmenu()
while(not quit_flag):
operation=raw_input(“请在此处输入菜单命令>”)
doswitch(operation)
if __name__==’__main__’:
main()
## do something
##—————————————————-

Posted in 未分类

发表评论