Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: ipp2_0_palindromes.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script demonstrates "Chapter 2: Project #2 - Finding Palindromes" from the book "Impractical Python Projects" by Lee Vaughan.
- - The script searches an English language dictionary file for palindromes and prints them out.
- Requirements:
- - Python 3.x
- - The following modules:
- - sys module
- - requests module
- Functions:
- - download_dictionary(url, file_name):
- - Description:
- - Downloads a dictionary file from a given URL.
- - Parameters:
- - url (str): The URL from which to download the dictionary file.
- - file_name (str): The name to save the downloaded file as.
- - load_dictionary(file):
- - Description:
- - Opens a text file and turns its contents into a list of lowercase strings.
- - Parameters:
- - file (str): The name of the file to open.
- - Returns:
- - list: A list of lowercase strings containing the words from the file.
- - find_palindromes(word_list):
- - Description:
- - Finds palindromes in a list of words.
- - Parameters:
- - word_list (list): A list of words to search for palindromes.
- - Returns:
- - list: A list of palindromes found in the input word list.
- Usage:
- - Ensure you have Python 3.x installed on your system.
- - Save the script to a file, for example, `palindromes.py`.
- - Run the script using the command: python palindromes.py.
- Running the Script:
- - Open a terminal or command prompt.
- - Navigate to the directory where the script is saved.
- - Run the script using the command: python palindromes.py.
- Output:
- - Upon running the script, any palindromes found in the dictionary file will be printed to the console.
- """
- import sys
- import requests
- def download_dictionary(url, file_name):
- """
- Download a dictionary file from a URL.
- Parameters:
- url (str): The URL from which to download the dictionary file.
- file_name (str): The name to save the downloaded file as.
- """
- try:
- response = requests.get(url) # Sending a GET request to the specified URL
- with open(file_name, 'wb') as f: # Opening the file in binary write mode
- f.write(response.content) # Writing the content of the response to the file
- except requests.RequestException as e:
- # Handling exceptions that may occur during the request
- print("Error downloading dictionary from {}: {}".format(url, e))
- sys.exit(1) # Exiting the program with an error code if an exception occurs
- def load_dictionary(file):
- """
- Open a text file & turn contents into a list of lowercase strings.
- Parameters:
- file (str): The name of the file to open.
- Returns:
- list: A list of lowercase strings containing the words from the file.
- """
- try:
- with open(file, encoding='utf-8') as in_file:
- # Opening the file with utf-8 encoding and reading its contents
- loaded_txt = in_file.read().strip().split('\n') # Splitting the text into lines
- loaded_txt = [x.lower() for x in loaded_txt] # Converting all words to lowercase
- return loaded_txt # Returning the list of lowercase words
- except IOError as e:
- # Handling IO errors that may occur during file operations
- print("{}\nError opening {}. Terminating program.".format(e, file))
- sys.exit(1) # Exiting the program with an error code if an exception occurs
- def find_palindromes(word_list):
- """
- Find palindromes in a list of words.
- Parameters:
- word_list (list): A list of words to search for palindromes.
- Returns:
- list: A list of palindromes found in the input word list.
- """
- palindrome_list = [] # Initializing a list to store palindromes
- for word in word_list:
- if len(word) > 1 and word == word[::-1]: # Checking if the word is a palindrome
- palindrome_list.append(word) # Adding the palindrome to the list
- return palindrome_list # Returning the list of palindromes
- def save_to_file(palindrome_list):
- """
- Save list of palindromes to a file.
- Parameters:
- palindrome_list (list): A list of palindromes to save.
- """
- try:
- with open("palindromes_list.txt", "w", encoding="utf-8") as f:
- for palindrome in palindrome_list:
- f.write("{}\n".format(palindrome)) # Writing each palindrome to the file
- print("Palindromes list saved to 'palindromes_list.txt'.")
- except IOError as e:
- print("Error saving palindromes list: {}".format(e))
- def main():
- dictionary_url = "https://inventwithpython.com/dictionary.txt"
- dictionary_file = "dictionary.txt"
- download_dictionary(dictionary_url, dictionary_file) # Downloading the dictionary file
- word_list = load_dictionary(dictionary_file) # Loading the dictionary into a list
- palindromes = find_palindromes(word_list) # Finding palindromes in the dictionary
- print("Number of palindromes found = {}".format(len(palindromes)))
- print(*palindromes, sep='\n') # Printing each palindrome on a new line
- save_option = input("Do you want to save the list of palindromes to a file? (y/n): ")
- if save_option.lower() == "y":
- save_to_file(palindromes) # Prompting the user to save the list if desired
- if __name__ == "__main__":
- main() # Calling the main function when the script is executed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement