Python for simple phone-based functionality

Source: Internet
Author: User
myphonebook2.py

#!/usr/bin/python#-*-coding:utf-8-*-import reclass Phonebook (object): "This is a phone book script. The script can implement Addcontact: Add contact information showcontact: Find name Show Contact Savecontacts: Store Contact to TXT document (storage format-Name: number/number) Loadcontacts: Loading a link from a TXT document Person "def __init__ (self): Self.contactsdict = {} def addcontact (self): while true:name = raw_input (' Please enter name &G           T;>> ') name = Name.strip () # Name must contain valid characters if name! = ': Break print ' * * * name cannot be empty ' While true:number = raw_input (' Please enter Number >>> ') Number = Re.sub (R ' \d ', ', #) # Remove the non-numeric characters I      F Number! = ": Break print ' * * * # can only be number ' cover = True #若联系人已存在, whether to overwrite if Self.contactsDict.has_key (name): print ' * * * * Contact already exists ' self. Showcontact (name) while True:control = Raw_input ("Input" C ": Overwrite the original number enter" n ": Keep the original number and store the new number enter" Q "to exit \n>>>" ' If control.lower () = = ' n ': Cover = False if control.lower () = = ' C ': Brea K If Control.lowER () = = ' Q ': return None print ' * * * input error ' if cover:self.contactsdict[name] = number else: If number in Self.contactsdict[name]: print ' * * * numbers already exist ' else:self.contactsdict[name] = Self.conta Ctsdict[name] + '/' + number def showcontact (self, name): print ' ++++++++++++++++++++++++ ' if Self.contactsDict.has _key (name): print ' "Contact info" ' print ' "Name:%s" '% name numberlist = self.contactsdict[name].split ('/') fo R num in range (len (numberlist)): print ' "Number%d:%s" '% (num+1, numberlist[num]) else:print ' "Contact%s not found"      '% name print ' ++++++++++++++++++++++++ ' def deletenumber (self, name): If Self.contactsDict.has_key (name): Self. Showcontact (name) Number = Self.contactsdict[name].split ('/') while True:print "" Enter the ordinal or enter "a" to delete The contact or enter "Q" to exit (do not delete) (if the contact number is deleted all, the contacts will also be deleted) ' control = raw_input (' >>> ') if control.lower () = = ' Q '  : Break      Elif control.lower () = = ' A ': Del Self.contactsdict[name] Break elif control.isdigit () and I          NT (Control) <= len (number): Del number[int (Control)-1] self.contactsdict[name] = '/'. Join (number) Break Else:print ' * * * input wrong ' def loadcontacts (self): ' Try:phonebook = open (' Phonebook . txt ', ' A + ') contacts = Phonebook.read () if contacts = = ': print ' * * * phone book is empty ' Else:contactsli st = Contacts.split (' \ n ') for the contact in contactslist:if = = = ": contact = contact. Split (': ') name = contact[0] Number = contact[1] self.contactsdict[name] = number fina Lly:PhoneBook.close () ' self.contactsdict = {line.split (': ') [0]: Line.split (': ') [1] for line in open (' Phoneb Ook.txt ', ' A + '). ReadLines ()} def savecontacts (self): try:if self.contactsDict:PhoneBook = open (' Phoneb Ook.txt ', ' W ') foR name, number in Self.contactsDict.items (): line = name + ': ' + # Phonebook.write (line) P Honebook.write (' \ n ') else:print ' * * * * No contact information ' finally:PhoneBook.close () if __name__ = = '  __main__ ': Myphonebook = Phonebook () myphonebook.loadcontacts () try:while true:raw_input (' press ENTER to continue ') print      "--------------------------------Enter a: Add contact input s: Show contact information input D: Delete Contact input Q: Exit--------------------------------' Control = raw_input (' >>> ') if control.lower () = = ' A ': Myphonebook.addcontact () elif Control.lo Wer () = = ' s ': name = raw_input (' Please enter the name of the contact you want to find \n>>> ') myphonebook.showcontact (name) elif control . lower () = = ' d ': name = raw_input (' Please enter the name of the contact you want to delete \n>>> ') myphonebook.deletenumber (name) elif con Trol.lower () = = ' Q ': Break else:print ' * * * input error ' finally:myPhoneBook.SaveContacts ()

Spent an afternoon and half a night writing this simple address book:
Haha, the first time to write such a long Python code, self-thinking structure is quite reasonable.
The code is as follows:

#-*-coding:utf-8-*-# file:addrList.py # date:2011-10-24 15:40:13 # Design a basic Address Book management program that has the ability to add, delete, edit, find, and more. # requires implementation in any language in C/c++,java,javascript,python. Character interface.  # no GUI required (graphical interface) 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 usage: Enter the commands in the menu to perform the action! The "print" available menu commands are as follows: "ShowMenu () def showmenu (): print" +****************** Action menu ***********************+ "print" | view All contact person (All) |   Find a contact (find) | Print "| Add a contact person (add) |   Delete a contact (remove) | Print | Edit Contact |   Save and Exit (save) | Print "| Use Help |   Quit without saving (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": Dosav E () elif op = = "Help": Help () elif op = = "Quit": Doquit () else:showerror ("Error: The command you entered is incorrect, please retype it.) Please enter help! if you need 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]) >: _flag = False print "The name is too long!" "If not _rphone.match (Items[1]): _flag = False print" Phone number format incorrect "If not _rqq.match (Items[2]): _flag = Fal     SE print "QQ number input Error" Return _flag def buildaddr (addr): _addr={} items=addr.split () If Len (items) < 3: Print "You have entered too little information" 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_co Unt]=_addr def init (): If not Os.path.isfile (addrs_list): Return of None Faddr=open (addrs_list, "R") for line in F Addr: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[' Pho Ne '],addr[' QQ ')) Faddr.flush () faddr.close () def doall (): Global _addrs_dict If Len (_addrs_dict) < 1:PR int "There is no record in the contact person!" "Return None printhead () for key,addr in _addrs_dict.items (): Printaddr (KEY,ADDR) def dofind (): _flag=fals E flag1=flag2=flag3=false cond=raw_input ("Please enter query Information:>") Debug ("Debug:{0}". Format (cond)) If Len (cond) = = 0:re Turn None if Cond.isdigit (): Flag1=findbyid (int (cond,10)) Flag2=findbyphone (COND) FLAG3=FINDBYQQ (cond) Els E:flaG1=findbyname (cond) _flag = Flag1 or Flag2 or flag3 if not _flag:print "no contacts found!" "Def Doadd (): line = raw_input (" Please enter the contact's name, phone number, QQ number > ") If Len (line) = = 0:return None addaddr (line) de F Existsid (_ID): Global _addrs_dict return _addrs_dict.has_key (_id) # if _id > _addrs_count or _id < 1: # RE Turn False # Else: # return True def doremove (): FLAG = True while Flag:key=raw_input ("Enter the number of the contact you want to delete (cancel please enter # ) if key = = ' # ': FLAG = False Continue if not existsid (int (key,10)): print "There is no contact for the number you entered. Please confirm that the contact information for the "continue print" number {0} is as follows: ". Format (key) Printbyid (int (key,10)) Yesorno=raw_input (" You are sure you want to delete the Do you have a contact? (y/n) "If Yesorno in" YY ": Removebyid (int (key,10)) print" Delete succeeded! "Yesorno=raw_input (" Do you still want to continue deleting contacts?) (y/n) ") if not yesorno in ' yY ': flag = False def doedit (): flag = True while Flag:key=raw_input (" Please enter The number of the contact to edit (cancel please enter #) print "debug:key:{0}". formaT (key) if key = = ' # ': FLAG = False Continue if not existsid (int (key,10)): print "There is no contact with the number you entered."     Please confirm that the contact information for "continue print" number {0} is as follows: ". 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 "Exiting ..."  Exit (0) def printhead (): print "+-----+----------+---------------+---------------+" print "| name |   Mobile Phone number |   QQ number | " 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 "Please enter new information for this contact, leave the original information blank," Name=raw_input ("Please enter a new name:>") If Len (name) > 0: _addr[' name ']=name phone=raw_input ("Please enter a new phone number:>") If Len (phone) > 0: _addr[' phone ']=phone qq=raw_input ( "Please enter the new QQ number:>") If Len (QQ) > 0: _addr[' qq ']=qq _addrs_dict[_id]=_addr print "updated successfully!      The new information for the "print" contact is as follows: "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 (NA Me): Return Findbyfield (name, ' name ') def findbyphone (phone): Return Findbyfield (phone, ' phone ') def FINDBYQQ (QQ): R Eturn Findbyfield (QQ, ' QQ ') def main (): Init () ShowMenu () and (not Quit_flag): Operation=raw_input ("Enter the menu command here > ") doswitch (operation) if __name__==' __main__ ': Main () # # do something # #----------------------------------------------------  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.