Python implements the simple phone book Function

Source: Internet
Author: User
This article describes how to implement the simple phone book function in Python, including adding contact information, searching for display contacts by name, and storing contacts to TXT documents, for more information, see myPhoneBook2.py.

#! /Usr/bin/python #-*-coding: UTF-8-*-import reclass PhoneBook (object): ''' this is a phone book script. This script can implement AddContact: add contact information ShowContact: Find name display contact SaveContacts: store the contact to the TXT document (storage format -- name: Number/Number) LoadContacts: load the contact ''' def _ init _ (self) from the txt file: self. contactsDict ={} def AddContact (self): while True: name = raw_input ('enter your name >>> ') name = name. strip () # The name must contain the valid character if name! = '': Break print '*** name cannot be blank' while True: number = raw_input ('Enter the number >>> ') number = re. sub (R' \ d', '', number) # Delete non-numeric characters in the number if number! = '': Break print '*** the number can only be a number 'Cover = True # if the contact already exists, whether to overwrite if self. contactsDict. has_key (name): print '*** the contact already exists 'self. showContact (name) while True: control = raw_input (''' input "c": overwrite the original number input "n ": retain the original number and store the new number. Enter "q" and exit \ n >>> ''') if control. lower () = 'N': cover = False break if control. lower () = 'C': break if control. lower () = 'q': return None print '*** input error 'if cover: self. contactsDict [name] = number else: if number in self. contactsDict [name]: print '*** number already exists 'else: self. contactsDict [name] = self. contactsDict [name] + '/' + number def ShowContact (self, name ): print '++' if self. contactsDict. has_key (name): print '[contact information] 'print' [name: % s] '% name numberList = self. contactsDict [name]. split ('/') for 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 serial number of the number to be deleted, enter "a" to delete the contact, or enter "q" to exit (not delete) (if all the contact numbers are deleted, the contact 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 int (control) <= len (number): del number [int (control)-1] self. contactsDict [name] = '/'. join (number) break else: print *** input error 'def LoadContacts (self): ''' try: PhoneBook = open('PhoneBook.txt ', 'a +') contacts = PhoneBook. read () if contacts = '': print '*** the phone book is empty. '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' *** no contact information 'Finally: PhoneBook. close () if _ name _ = '_ main _': myPhoneBook = PhoneBook () myPhoneBook. loadContacts () try: while True: raw_input ('Press the Enter key to continue ') print ''' ---------------------------------- input a: Add a contact input s: Show Contact Information Input d: delete a contact input q: exit -------------------------------- '''control = raw_input ('>>>') if control. lower () = 'A': myPhoneBook. addContact () elif control. lower () ='s ': name = raw_input (' enter the name of the contact to be searched \ n >>') myPhoneBook. showContact (name) elif control. lower () = 'D': name = raw_input ('enter the name of the contact to be deleted \ n >>') myPhoneBook. deleteNumber (name) elif control. lower () = 'q': break else: print '*** incorrect input 'Finally: myPhoneBook. saveContacts ()

It took me one afternoon and half a night to write this simple address book:
Haha, for the first time I wrote such a long Python code, I think the structure is quite reasonable.
The Code is as follows:

#-*-Coding: UTF-8-*-# file: addrList. py # date: 15:40:13 # design a basic Address Book Management Program to provide functions such as adding, deleting, editing, and searching. # Use any language in C/C ++, java, javascript, and python. Character interface. # No GUI (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 h Elp (): print "Usage: Enter the command in the menu to perform the corresponding operation! "Print" available menu command: "showMenu () def showMenu (): print "+ ****************** operation menu ***************** * ***** + "print" | view all contacts (all) | find | "print" | add | Delete | print | edit | save) | "print" | help | exit but not save (quit) | "print" + _____________________________________________________ + "def showError (info): print info def doSwitch (op ): if op = "all": doAll () elif op = "fi Nd ": 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 ("error: the command you entered is incorrect. Please enter it again. Enter help for 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 "the name is too long! "If not _ rPhone. match (items [1]): _ flag = False print "Incorrect Mobile Phone Number Format" if not _ rQQ. match (items [2]): _ flag = False print "Incorrect QQ number input" return _ flag def buildAddr (addr): _ addr ={} items = addr. split () if len (items) <3: print "you input 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_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 (ad Dr ['name'], addr ['phone'], addr ['qq']) faddr. flush () faddr. close () def doAll (): global _ addrs_dict if len (_ addrs_dict) <1: print "no records in contacts! "Return None printHead () for key, addr in _ addrs_dict.items (): printAddr (key, addr) def doFind (): _ flag = False flag1 = flag2 = flag3 = False cond = raw_input ("Enter the query information:>") 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 "No Find any contacts! "Def doAdd (): line = raw_input (" Enter the contact name, mobile phone number, QQ number> ") 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 ("Enter the ID of the contact to be deleted (cancel the operation and enter #)") if key = '#': FLAG = False continue if not existsId (int (key, 10): print "not saved In the contact you enter. Make sure that the contact information of "continue print" numbered {0} is as follows :". format (key) printById (int (key, 10) yesOrNo = raw_input ("are you sure you want to delete the above contact? (Y/n) ") if yesOrNo in" yY ": removeById (int (key, 10) print" deleted successfully! "YesOrNo = raw_input (" Do you still need to delete the contact? (Y/n) ") if not yesOrNo in" yY ": FLAG = False def doEdit (): FLAG = True while FLAG: key = raw_input ("Enter the ID of the contact you want to edit (cancel entering #)") print "DEBUG: key: {0 }". format (key) if key = '#': FLAG = False continue if not existsId (int (key, 10): print "the contact you entered does not exist. Make sure that the contact information of "continue print" numbered {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 = True print "exiting ...... "# Exit (0) def printHead (): print "+ ----- + ---------- + --------------- + ------------- +" print "| No. | 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 "Enter new information for this contact, if this parameter is left blank, the original information "name = raw_input (" enter a new name:> ") if len (name)> 0: _ addr ['name'] = name phone = raw_input ("enter a new phone number:>") if len (phone)> 0: _ addr ['phone'] = phone qq = raw _ Input ("enter a new qq number:>") if len (qq)> 0: _ addr ['qq'] = QQ _ addrs_dict [_ id] = _ addr print "updated successfully! "Print" new contact information: "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 ("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.