Python 實(shí)現(xiàn)簡單的電話本功能
myPhoneBook2.py
#!/usr/bin/python # -*- coding: utf-8 -*- import re class PhoneBook(object): '''這是一個(gè)電話簿腳本。 該腳本能夠?qū)崿F(xiàn) AddContact:添加聯(lián)系人信息 ShowContact:查找姓名顯示聯(lián)系人 SaveContacts:存儲聯(lián)系人到 TXT 文檔(存儲格式——姓名:號碼/號碼) LoadContacts:從 txt 文檔中載入聯(lián)系人 ''' 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) # 刪除號碼中的非數(shù)字字符 if number != '': break print '***號碼只能是數(shù)字' cover = True #若聯(lián)系人已存在,是否覆蓋 if self.contactsDict.has_key(name): print '***聯(lián)系人已存在' 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 '***輸入錯(cuò)誤' if cover: self.contactsDict[name] = number else: if number in self.contactsDict[name]: print '***號碼已經(jīng)存在' else: self.contactsDict[name] = self.contactsDict[name] + '/' + number def ShowContact(self, name): print '++++++++++++++++++++++++' if self.contactsDict.has_key(name): print '【聯(lián)系人信息】' print '【姓名: %s】' % name numberList = self.contactsDict[name].split('/') for num in range(len(numberList)): print '【號碼%d: %s】' % (num+1, numberList[num]) else: print '【找不到聯(lián)系人%s】' % name print '++++++++++++++++++++++++' def DeleteNumber(self, name): if self.contactsDict.has_key(name): self.ShowContact(name) number = self.contactsDict[name].split('/') while True: print ''' 請輸入要?jiǎng)h除號碼的序號 或者輸入 "a" 刪除該聯(lián)系人 或者輸入 "q" 退出(不刪除) (若聯(lián)系人號碼被全部刪除,該聯(lián)系人也將被刪除)''' control = raw_input('>>>') if control.lower() == 'q': break elif control.lower() == 'a': del self.contactsDict[name] break elif control.isdigit() and int(control) <= len(number): del number[int(control)-1] self.contactsDict[name] = '/'.join(number) break else: print '***輸入有誤' def LoadContacts(self): ''' try: PhoneBook = open('PhoneBook.txt', 'a+') contacts = PhoneBook.read() if contacts == '': print '***電話簿為空' else: ContactsList = contacts.split('\n') for contact in ContactsList: if not contact == '': contact = contact.split(':') name = contact[0] number = contact[1] self.contactsDict[name] = number finally: PhoneBook.close() ''' self.contactsDict = {line.split(':')[0]: line.split(':')[1] for line in open('PhoneBook.txt','a+').readlines()} def SaveContacts(self): try: if self.contactsDict: PhoneBook = open('PhoneBook.txt', 'w') for name, number in self.contactsDict.items(): line = name + ':' + number PhoneBook.write(line) PhoneBook.write('\n') else: print '***沒有聯(lián)系人信息' finally: PhoneBook.close() if __name__ == '__main__': myPhoneBook = PhoneBook() myPhoneBook.LoadContacts() try: while True: raw_input('按回車鍵繼續(xù)') print ''' -------------------------------- 輸入 a:添加聯(lián)系人 輸入 s:顯示聯(lián)系人信息 輸入 d:刪除聯(lián)系人 輸入 q:退出 --------------------------------''' control = raw_input('>>>') if control.lower() == 'a': myPhoneBook.AddContact() elif control.lower() == 's': name = raw_input('請輸入要查找的聯(lián)系人姓名\n>>>') myPhoneBook.ShowContact(name) elif control.lower() == 'd': name = raw_input('請輸入要?jiǎng)h除的聯(lián)系人姓名\n>>>') myPhoneBook.DeleteNumber(name) elif control.lower() == 'q': break else: print '***輸入有誤' finally: myPhoneBook.SaveContacts()
花了一個(gè)下午和半個(gè)晚上寫了這個(gè)簡單通訊錄:
哈哈,第一次寫這么長的Python代碼,自認(rèn)為結(jié)構(gòu)還是挺合理的。
代碼如下:
#-*- coding:utf-8 -*- # file :addrList.py # date :2011-10-24 15:40:13 # 設(shè)計(jì)一個(gè)基本的通訊錄管理程序,使其具有添加,刪除,編輯,查找等功能。 # 要求使用C/C++,java,javascript,python中任意一種語言實(shí)現(xiàn)。字符界面即可。 # 不需要有GUI(圖形界面) import sys import os import string import re from datetime import datetime QUIT_FLAG = False ADDRS_LIST = "addr_list.txt" _addrs_dict = {} _addrs_count = 0 DEBUG=2 def info(message): global DEBUG if DEBUG > 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 "用法:輸入菜單中的命令即可執(zhí)行相應(yīng)操作!" print "可用菜單命令如下:" showMenu() def showMenu(): print "+******************操作菜單***********************+" print "|查看所有聯(lián)系人(all) | 查找聯(lián)系人(find) |" print "|添加聯(lián)系人(add) | 刪除聯(lián)系人(remove) |" print "|編輯聯(lián)系人(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("錯(cuò)誤:您輸入的命令有誤,請重新輸入。需要幫助請輸入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 "手機(jī)號碼格式不正確" 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 "聯(lián)系人當(dāng)中暫無記錄!" 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 "沒有查找到任何聯(lián)系人!" def doAdd(): line = raw_input("請依次輸入聯(lián)系人的姓名,手機(jī)號碼,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("請輸入要?jiǎng)h除的聯(lián)系人的編號(取消請輸入#)") if key == '#': FLAG = False continue if not existsId(int(key,10)): print "不存在您所輸入編號的聯(lián)系人。請確認(rèn)" continue print "編號為 {0} 的聯(lián)系人信息如下:".format(key) printById(int(key,10)) yesOrNo=raw_input("您確定要?jiǎng)h除上述聯(lián)系人嗎?(y/n)") if yesOrNo in "yY": removeById(int(key,10)) print "刪除成功!" yesOrNo=raw_input("您還需要繼續(xù)刪除聯(lián)系人嗎?(y/n)") if not yesOrNo in "yY": FLAG = False def doEdit(): FLAG = True while FLAG: key=raw_input("請輸入要編輯的聯(lián)系人的編號(取消請輸入#)") print "DEBUG:key:{0}".format(key) if key == '#': FLAG = False continue if not existsId(int(key,10)): print "不存在您所輸入編號的聯(lián)系人。請確認(rèn)" continue print "編號為 {0} 的聯(lián)系人信息如下:".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 "|編號 | 姓名 | 手機(jī)號碼 | 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 "請輸入該聯(lián)系人的新信息,相應(yīng)留空則保留原有信息" name=raw_input("請輸入新姓名:>") if len(name) > 0: _addr['name']=name phone=raw_input("請輸入新手機(jī)號碼:>") if len(phone) > 0: _addr['phone']=phone qq=raw_input("請輸入新的QQ號碼:>") if len(qq) > 0 : _addr['QQ']=qq _addrs_dict[_id]=_addr print "更新成功!" print "聯(lián)系人新的信息如下:" 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("請?jiān)诖颂庉斎氩藛蚊?gt;") doSwitch(operation) if __name__=='__main__': main() ## do something ##----------------------------------------------------
相關(guān)文章
python用opencv將標(biāo)注提取畫框到對應(yīng)的圖像中
這篇文章主要介紹了python用opencv將標(biāo)注提取畫框到對應(yīng)的圖像中,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08python實(shí)現(xiàn)跨excel sheet復(fù)制代碼實(shí)例
這篇文章主要介紹了python實(shí)現(xiàn)跨excel sheet復(fù)制代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03Matplotlib實(shí)戰(zhàn)之堆疊面積圖繪制詳解
堆疊面積圖和面積圖都是用于展示數(shù)據(jù)隨時(shí)間變化趨勢的統(tǒng)計(jì)圖表,但它們的特點(diǎn)有所不同,堆疊面積圖既能看到各數(shù)據(jù)系列的走勢,又能看到整體的規(guī)模,下面我們就來看看如何繪制堆疊面積圖吧2023-08-08python?matplotlib實(shí)現(xiàn)條形圖的填充效果
這篇文章主要為大家詳細(xì)介紹了python?matplotlib實(shí)現(xiàn)條形圖的填充效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04Python selenium如何設(shè)置等待時(shí)間
這篇文章主要為大家詳細(xì)介紹了Python selenium如何設(shè)置等待時(shí)間,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09Python+OpenCV圖像處理——實(shí)現(xiàn)直線檢測
這篇文章主要介紹了Python+OpenCV如何實(shí)現(xiàn)直線檢測,幫助大家更好的利用python處理圖片,感興趣的朋友可以了解下2020-10-10