简易Python电话本(Simple Python Telephone Book)
[*]#!/usr/bin/python
[*]'''''
[*]Compiler:Python2.6
[*]Filename:tb.py
[*]Version:1.00@20081205
[*]Author:t0nsha
[*](liaodunxia{at}gmail.com)
[*]Remark:Justasimpletelephonebookprogram
[*]formyoneweekpythonstudy.
[*]'''
[*]
[*]importcPickleasp
[*]tbDict={}
[*]tbdat='tb.dat'
[*]
[*]classPerson:
[*]def__init__(self,name,phone,email,address):
[*]self.name=name
[*]self.phone=phone
[*]self.email=email
[*]self.address=address
[*]
[*]deftbAdd(a):
[*]whileTrue:
[*]name=raw_input('EnteranameforAdd:')
[*]ifname=='Q':
[*]break
[*]iftbDict.has_key(name):
[*]print'%salreadyexists.'%name
[*]continue
[*]phone=raw_input('phone:')
[*]email=raw_input('email:')
[*]address=raw_input('address:')
[*]person=Person(name=name,/
[*]phone=phone,/
[*]email=email,/
[*]address=address)
[*]tbDict=person
[*]print'%sadded,total:%d.'%(name,len(tbDict))
[*]ifa!='A':
[*]break
[*]
[*]deftbRemove(r):
[*]whileTrue:
[*]name=raw_input('EnteranameforDelete:')
[*]ifname=='Q':
[*]break
[*]ifnottbDict.has_key(name):
[*]print'%snotexist.'%name
[*]else:
[*]deltbDict
[*]print'%sremoved.'%name
[*]ifr!='R':
[*]break
[*]
[*]deftbSearch(s):
[*]whileTrue:
[*]name=raw_input('EnteranameforSearch:')
[*]ifname=='Q':
[*]break
[*]iftbDict.has_key(name):
[*]print'name:'.rjust(12),tbDict.name
[*]print'phone:'.rjust(12),tbDict.phone
[*]print'email:'.rjust(12),tbDict.email
[*]print'address:'.rjust(12),tbDict.address
[*]else:
[*]print'%snotfound.'%name
[*]ifs!='S':
[*]break
[*]
[*]deftbList(l):
[*]ifl=='l':
[*]forkeyintbDict.keys():
[*]printkey
[*]elifl=='L':
[*]fornameintbDict.keys():
[*]print'name:'.rjust(12),tbDict.name
[*]print'phone:'.rjust(12),tbDict.phone
[*]print'email:'.rjust(12),tbDict.email
[*]print'address:'.rjust(12),tbDict.address
[*]print'total:%d.'%len(tbDict)
[*]
[*]deftbModify(m):
[*]whileTrue:
[*]name=raw_input('EnteranameforModify:')
[*]ifname=='Q':
[*]break
[*]ifnottbDict.has_key(name):
[*]print'%snotexist.'%name
[*]return
[*]phone=raw_input('newphone:')
[*]email=raw_input('newemail:')
[*]address=raw_input('newaddress:')
[*]person=Person(name=name,/
[*]phone=phone,/
[*]email=email,/
[*]address=address)
[*]tbDict=person
[*]print'%smodified.'%(name)
[*]ifm!='M':
[*]break
[*]
[*]deftbUsage():
[*]print'''''
[*]Usage:
[*]a/A-->addanewperson/loopadd
[*]l/L-->listallnames/listalldetails
[*]r/S-->removeone/loopremove
[*]s/S-->search/loopsearch
[*]q/Q-->quit&save/quit(loop)butnotsave
[*]'''
[*]
[*]deftbQuit(q):
[*]ifq=='q':
[*]p.dump(tbDict,file(tbdat,'w+'))
[*]
[*]deftbLoop():
[*]whileTrue:
[*]c=raw_input('Readytowork:')
[*]ifc=='a'orc=='A':
[*]tbAdd(c)
[*]elifc=='l'orc=='L':
[*]tbList(c)
[*]elifc=='m'orc=='M':
[*]tbModify(c)
[*]elifc=='r'orc=='R':
[*]tbRemove(c)
[*]elifc=='s'orc=='S':
[*]tbSearch(c)
[*]elifc=='q'orc=='Q':
[*]tbQuit(c)
[*]break
[*]else:
[*]tbUsage()
[*]
[*]#Whilefirstrun,file"tb.dat"doesn'texist,this
[*]#willraiseanIOErrorexception,butweigoredit.
[*]try:
[*]tbDict=p.load(file(tbdat))
[*]exceptIOError:
[*]pass
[*]tbLoop()
[*]
[*]
[*]
页:
[1]