Advertisement
pyzuki

phone_book.py

Sep 8th, 2011
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. # phone_book_tutor.py
  2.  
  3. """
  4. phone_book.txt:
  5.  
  6. bp1=xxx
  7. bp2=ooo
  8. ch=zzz
  9. me=aaa
  10. mg=vvv
  11. pu1=bbb
  12. pu2=ccc
  13. pw=kkk
  14. """
  15. p = {}
  16. file = open("C:/P32Working/Data/phone_book.txt")
  17. lines = file.readlines()
  18. for line in lines:
  19.     key = line.partition('=')[0]
  20.     value = line.partition('=')[2][:-1]
  21.     p[key] = value
  22.  
  23. def consolidate_keys_with_digits(keys_list):
  24.     """
  25.    Given a list of dictionary keys, returns a list identical to that list except that
  26.     keys ending in a digit have that digit removed; any resulting duplicate keys are    deleted;
  27.    and the list is sorted.
  28.    
  29.    >>> keys_list
  30.    [gp, mm1, mm2, er]
  31.    >>> consolidate_keys_with_digits(keys_list)
  32.    [er, mm, gp]
  33.    """
  34.     consolidated_keys_list = []
  35.     for x in keys_list:
  36.         if x[-1] in '0123456789':
  37.             consolidated_keys_list.append(x[:-1])
  38.         else:
  39.             consolidated_keys_list.append(x)
  40.     list_set = set(consolidated_keys_list)
  41.     consolidated_keys_list = list(list_set)
  42.     consolidated_keys_list.sort()
  43.     return consolidated_keys_list
  44.  
  45. while True:
  46.     print()
  47.     print("Enter initials of name, or 'all' to print phone book, or 'q' to quit.")
  48.     try:
  49.         initials = input("Enter: ").lower()
  50.         print()
  51.        
  52.         if initials == 'q':
  53.             print("Bye.")
  54.             break
  55.         elif initials == 'all':
  56.             list_all = list(p.items())
  57.             list_all.sort()
  58.             for x in list_all:
  59.                 print(x)
  60.         else:
  61.             print(p[initials])
  62.            
  63.     except KeyError:
  64.         keys_list = list(p.keys())
  65.         consolidated_keys_list = consolidate_keys_with_digits(keys_list)
  66.         initials_found_list = []
  67.         for x in '0123456789':
  68.             if (initials + x) in keys_list:
  69.                 initials_found_list.append(initials + x)
  70.         if initials_found_list:
  71.             for x in initials_found_list:
  72.                 print(p[x])
  73.         elif initials == '':
  74.             print("You didn't enter anything.")
  75.         else:
  76.             print("The initials '", initials, "' are not in phone book.", sep='')
  77.             print("This is the list of entry initials:")
  78.             print(consolidated_keys_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement