Advertisement
Python253

ipp2_0_palindromes

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