Facebook
From Bistre Pig, 3 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 51
  1. import re
  2. import json
  3. import os
  4. import random
  5. from datetime import datetime
  6. from time import gmtime, strftime
  7. import requests
  8. from bs4 import BeautifulSoup
  9. from termcolor import colored
  10.  
  11. """ phone book menu"""
  12.  
  13. CONTACTS_FILE_NAME = "contacts_json.json"
  14.  
  15.  
  16. def read_contacts_from_file():
  17.     if os.path.exists(CONTACTS_FILE_NAME):
  18.         with open(CONTACTS_FILE_NAME, "r") as f:
  19.             return json.load(f)
  20.     else:
  21.         return []
  22.  
  23.  
  24. def save_contacts_to_file(contacts):
  25.     with open(CONTACTS_FILE_NAME, "w") as f:
  26.         return json.dump(contacts, f, indent=2)
  27.  
  28.  
  29. def find_contact(id, contacts):
  30.     for contact in contacts:
  31.         if contact['id'] == id:
  32.             return contact
  33.  
  34.  
  35. def delete_contact(id, contacts):
  36.     contact = find_contact(id, contacts)
  37.     if not contact:
  38.         raise Exception("no contact by id {} in file".format(id))
  39.     contacts.remove(contact)
  40.     print("\ndeleted contact successfully!!")
  41.     save_contacts_to_file(contacts)
  42.  
  43.  
  44. def add_contact(id, name, last_name, date_of_birth, phone_number, contacts):
  45.     if find_contact(id, contacts):
  46.         raise Exception("contact with id {} already exists in file".format(id))
  47.     contact = {"id": id, "name": name.capitalize(), "last_name": last_name.capitalize(), "date_of_birth": date_of_birth,
  48.                "phone_number": phone_number}
  49.     contacts.append(contact)
  50.     save_contacts_to_file(contacts)
  51.  
  52.  
  53. def show_contact(id, contacts):
  54.     contact = find_contact(id, contacts)
  55.     if not contact:
  56.         raise Exception("contact id {}  was not found in the file".format(id))
  57.     print("Name: {}".format(contact['name']))
  58.     print("Last Name: {}".format(contact['last_name']))
  59.     print("Date Of Birth: {}".format(contact['date_of_birth']))
  60.     print("Phone Number: {}".format(contact['phone_number']))
  61.     print("Number of ID results from google search:",
  62.           colored(google_search_results(contact['name'], contact['last_name']), 'yellow'))
  63.  
  64.  
  65. def show_contacts(contacts):
  66.     if len(contacts) == 0:
  67.         print('No contacts in file')
  68.     else:
  69.         line_format = "{:<20}" * 5
  70.         print(line_format.format('ID:', 'Name:', 'Last Name:', 'Date Of Birth:', 'Phone Number:'))
  71.         for contact in contacts:
  72.             print(line_format.format(
  73.                 contact['id'],
  74.                 contact['name'],
  75.                 contact['last_name'],
  76.                 contact['date_of_birth'],
  77.                 contact['phone_number']
  78.             ))
  79.  
  80.  
  81. def google_search_results(name, last_name):
  82.     """scrapes a Google search page to get results statistics"""
  83.     identity = name + '+' + last_name
  84.  
  85.     url = "https://www.google.com/search?source=hp&ei=wCCwXqb9DYmWa4-HlfAG&q={}&oq={}&gs_lcp=CgZwc3ktYWIQAzIFCAAQgwEyAggAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADICCAA6BAgAEAE6BAgAEApQ1idY1jRggThoAXAAeACAAfsBiAHAB5IBBTEuNi4xmAEAoAEBqgEHZ3dzLXdperABAA&sclient=psy-ab&ved=0ahUKEwim3fT9r5rpAhUJyxoKHY9DBW4Q4dUDCAc&uact=5 ".format(
  86.         identity, identity)
  87.     headers = {
  88.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
  89.     }
  90.  
  91.     response = requests.get(url, headers=headers)
  92.     """used BeautifulSoup Python library for pulling data out of HTML using module html parser."""
  93.     response_parsed = BeautifulSoup(response.text, features="html.parser")
  94.     result_stats_value = response_parsed.find('div', id='result-stats')
  95.     only_the_statistics = result_stats_value.contents[0][2:]
  96.     results_found = only_the_statistics.split(" ")
  97.     return results_found[0]
  98.  
  99.  
  100. def tip_of_the_day():
  101.     """using module requests to get the tip of the day from website"""
  102.     string = random.randrange(1, 217, 1)
  103.     web_site_response = requests.get("https://api.adviceslip.com/advice/{}".format(string))
  104.     adding_delimetter = web_site_response.text + str('}')
  105.     tip = json.loads(adding_delimetter)
  106.     return tip['slip']['advice']
  107.  
  108.  
  109. def print_options():
  110.     print("\nOptions:")
  111.     print("1. Show Contacts")
  112.     print("2. Add a Contact")
  113.     print("3. Show a Contact (by ID)")
  114.     print("4. Delete a Contact (by ID)")
  115.     print("5. Exit Phone Book")
  116.     print('\nTip of the day:')
  117.     print(colored(tip_of_the_day(), 'yellow'))
  118.  
  119.  
  120. def validation_read_int_id():
  121.     """
  122.     validation of id identity number  input  using regex method
  123.     """
  124.     while True:
  125.         try:
  126.             string = input()
  127.             """ return True if string contains regex pattern"""
  128.             regexp = re.compile(r'^[0-9]{9}$')
  129.             if regexp.search(string):
  130.                 return string
  131.             else:
  132.                 print("ID must be 9 digits, Please Try again:")
  133.         except ValueError:
  134.             print("Not an integer, Please Try again:")
  135.  
  136.  
  137. def validation_read_int_phone_number():
  138.     """
  139.     validation of phone number input  using regex method
  140.     """
  141.     while True:
  142.         try:
  143.             string = input()
  144.             """return True if string contains regex pattern"""
  145.             regexp = re.compile(r'^0([0-9]{8,9})$')
  146.             if regexp.search(string):
  147.                 return string
  148.             else:
  149.                 print("phone number must start with '0' and contain between 8-9 digits, Please Try again:")
  150.         except ValueError:
  151.             print("Only integers, Please Try again:")
  152.  
  153.  
  154. def validation_read_alphabet():
  155.     """
  156.     validation of input user input using isalpha method
  157.     """
  158.     while True:
  159.         user_input = input()
  160.         if not user_input.isalpha():
  161.             """isalpha-checks whether the string consists of alphabetic characters only"""
  162.             print("You must consist of letters only Please Try again:")
  163.         else:
  164.             return user_input
  165.  
  166.  
  167. def validate_date_time():
  168.     """
  169.     validation of date time from user input using strptime method
  170.     """
  171.     while True:
  172.         """returns an integer object from any number or string"""
  173.         user_input = input()
  174.         try:
  175.             """string to datetime (the class method takes two arguments string and format)"""
  176.             datetime.strptime(user_input, '%Y-%m-%d')
  177.             return str(user_input)
  178.         except ValueError:
  179.             print("Input should be date (YYYY-MM-DD) Please Try again")
  180.  
  181.  
  182. def phone_book():
  183.     """
  184.     Main program of "phone book" prints a menu and executes commands on the demand of the users' choice
  185.     """
  186.     print("\n", strftime("%a, %d %b %Y ", gmtime()), "\n++++++++++++++++++++++\n Welcome To Phone "
  187.                                                      "Book!!\n++++++++++++++++++++++")
  188.     choice = None
  189.     while choice != 5:
  190.         try:
  191.             print_options()
  192.             command_from_user = input("\nYour Selection: ")
  193.             choice = int(command_from_user)
  194.             contacts = read_contacts_from_file()
  195.             if choice == 1:
  196.                 show_contacts(contacts)
  197.             elif choice == 2:
  198.                 print("To add a contact please fill out:")
  199.                 print("ID: ")
  200.                 id = validation_read_int_id()
  201.                 print("Name: ")
  202.                 name = validation_read_alphabet()
  203.                 print("Last Name: ")
  204.                 last_name = validation_read_alphabet()
  205.                 print("Date Of Birth (YYYY-MM-DD): ")
  206.                 date_of_birth = validate_date_time()
  207.                 print("Phone Number: ")
  208.                 phone_number = validation_read_int_phone_number()
  209.                 add_contact(id, name, last_name, date_of_birth, phone_number, contacts)
  210.                 print("Contact Added Successfully to DB")
  211.             elif choice == 3:
  212.                 id = input("ID: ")
  213.                 show_contact(id, contacts)
  214.             elif choice == 4:
  215.                 id = input("ID: ")
  216.                 delete_contact(id, contacts)
  217.             elif choice == 5:
  218.                 print("bye!")
  219.         except Exception as e:
  220.             """If no exception occurs, the except clause is skipped and execution of the try statement is finished."""
  221.             print(e)
  222.  
  223.  
  224. if __name__ == "__main__":
  225.     phone_book()
  226.