Advertisement
Python253

ipp3_0_palingrams

May 31st, 2024
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.91 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: ipp3_0_palingrams.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script demonstrates "Chapter 2: Project #3 - Finding Palingrams" from the book "Impractical Python Projects" by Lee Vaughan.
  10.    - The script searches an English language dictionary file for palingrams (phrases that can be read both forward and backward, ignoring spaces and punctuation) and prints them out.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - The following modules:
  15.        - sys module
  16.        - requests module
  17.        - time module
  18.  
  19. Functions:
  20.    - download_dictionary(url, file_name):
  21.        - Description:
  22.            - Downloads a dictionary file from a given URL.
  23.            - Parameters:
  24.                - url (str): The URL from which to download the dictionary file.
  25.                - file_name (str): The name to save the downloaded file as.
  26.                
  27.    - load_dictionary(file):
  28.        - Description:
  29.            - Opens a text file and turns its contents into a list of lowercase strings.
  30.            - Parameters:
  31.                - file (str): The name of the file to open.
  32.            - Returns:
  33.                - list: A list of lowercase strings containing the words from the file.
  34.                
  35.    - find_palingrams():
  36.        - Description:
  37.            - Finds palingrams in a list of words loaded from a dictionary file.
  38.            - Prints the number of palingrams found and the runtime of the search.
  39.            - Prompts the user to save the list of palingrams to a file.
  40.                
  41.    - save_to_file(pali_list):
  42.        - Description:
  43.            - Saves a list of palingrams to a file.
  44.            - Parameters:
  45.                - pali_list (list): A list of tuples containing pairs of palingrams.
  46.                
  47. Usage:
  48.    - Ensure you have Python 3.x installed on your system.
  49.    - Save the script to a file, for example, `palingrams.py`.
  50.    - Run the script using the command: python palingrams.py.
  51.  
  52. Running the Script:
  53.    - Open a terminal or command prompt.
  54.    - Navigate to the directory where the script is saved.
  55.    - Run the script using the command: python palingrams.py.
  56.  
  57. Output:
  58.    - Upon running the script, any palingrams found in the dictionary file will be printed to the console.
  59.    - The number of palingrams found and the runtime of the search will be displayed.
  60.    - The list of palingrams will be saved to a file named 'palingrams_list.txt'.
  61. """
  62.  
  63. import sys
  64. import requests
  65. import time
  66.  
  67. def download_dictionary(url, file_name):
  68.     """Download a dictionary file from a URL."""
  69.     try:
  70.         response = requests.get(url)  # Sending a GET request to the specified URL
  71.         with open(file_name, 'wb') as f:  # Opening the file in binary write mode
  72.             f.write(response.content)  # Writing the content of the response to the file
  73.     except requests.RequestException as e:
  74.         # Handling exceptions that may occur during the request
  75.         print("Error downloading dictionary from {}: {}".format(url, e))
  76.         sys.exit(1)  # Exiting the program with an error code if an exception occurs
  77.  
  78. def load_dictionary(file):
  79.     """Open a text file & turn contents into a list of lowercase strings."""
  80.     try:
  81.         with open(file, encoding='utf-8') as in_file:
  82.             # Opening the file with utf-8 encoding and reading its contents
  83.             loaded_txt = in_file.read().strip().split('\n')  # Splitting the text into lines
  84.             loaded_txt = [x.lower() for x in loaded_txt]  # Converting all words to lowercase
  85.             return loaded_txt  # Returning the list of lowercase words
  86.     except IOError as e:
  87.         # Handling IO errors that may occur during file operations
  88.         print("{}\nError opening {}. Terminating program.".format(e, file))
  89.         sys.exit(1)  # Exiting the program with an error code if an exception occurs
  90.  
  91. def find_palingrams():
  92.     """Find dictionary palingrams."""
  93.     start_time = time.time()  # Getting the current time to measure the runtime
  94.     dictionary_url = "https://inventwithpython.com/dictionary.txt"
  95.     dictionary_file = "dictionary.txt"
  96.     download_dictionary(dictionary_url, dictionary_file)  # Downloading the dictionary file
  97.     word_list = load_dictionary(dictionary_file)  # Loading the dictionary into a list
  98.     pali_list = []  # Initializing a list to store palingrams
  99.     words = set(word_list)  # Converting the list of words into a set for faster lookup
  100.     for word in words:
  101.         end = len(word)
  102.         rev_word = word[::-1]
  103.         if end > 1:
  104.             for i in range(end):
  105.                 if word[i:] == rev_word[:end-i] and rev_word[end-i:] in words:
  106.                     pali_list.append((word, rev_word[end-i:]))
  107.                 if word[:i] == rev_word[end-i:] and rev_word[:end-i] in words:
  108.                     pali_list.append((rev_word[:end-i], word))
  109.     end_time = time.time()  # Getting the current time after finding palingrams
  110.     print("\nNumber of palingrams = {}\n".format(len(pali_list)))  # Printing the number of palingrams found
  111.     print("Runtime for finding palingrams was {} seconds.".format(end_time - start_time))  # Printing the runtime
  112.     save_option = input("\nDo you want to save the list of palingrams to a file? (y/n): ")
  113.     if save_option.lower() == "y":
  114.         save_to_file(pali_list)  # Prompting the user to save the list if desired
  115.  
  116. def save_to_file(pali_list):
  117.     """Save list of palingrams to a file."""
  118.     try:
  119.         with open("palingrams_list.txt", "w", encoding="utf-8") as f:
  120.             for palingram in pali_list:
  121.                 f.write("{} {}\n".format(palingram[0], palingram[1]))
  122.         print("\nPalingrams list saved to 'palingrams_list.txt'.")
  123.     except IOError as e:
  124.         print("\nError saving palingrams list: {}".format(e))
  125.  
  126. if __name__ == "__main__":
  127.     find_palingrams()  # Calling the find_palingrams function when the script is executed
  128.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement