Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: ipp3_0_palingrams.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script demonstrates "Chapter 2: Project #3 - Finding Palingrams" from the book "Impractical Python Projects" by Lee Vaughan.
- - 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.
- Requirements:
- - Python 3.x
- - The following modules:
- - sys module
- - requests module
- - time 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_palingrams():
- - Description:
- - Finds palingrams in a list of words loaded from a dictionary file.
- - Prints the number of palingrams found and the runtime of the search.
- - Prompts the user to save the list of palingrams to a file.
- - save_to_file(pali_list):
- - Description:
- - Saves a list of palingrams to a file.
- - Parameters:
- - pali_list (list): A list of tuples containing pairs of palingrams.
- Usage:
- - Ensure you have Python 3.x installed on your system.
- - Save the script to a file, for example, `palingrams.py`.
- - Run the script using the command: python palingrams.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 palingrams.py.
- Output:
- - Upon running the script, any palingrams found in the dictionary file will be printed to the console.
- - The number of palingrams found and the runtime of the search will be displayed.
- - The list of palingrams will be saved to a file named 'palingrams_list.txt'.
- """
- import sys
- import requests
- import time
- def download_dictionary(url, file_name):
- """Download a dictionary file from a URL."""
- 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."""
- 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_palingrams():
- """Find dictionary palingrams."""
- start_time = time.time() # Getting the current time to measure the runtime
- 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
- pali_list = [] # Initializing a list to store palingrams
- words = set(word_list) # Converting the list of words into a set for faster lookup
- for word in words:
- end = len(word)
- rev_word = word[::-1]
- if end > 1:
- for i in range(end):
- if word[i:] == rev_word[:end-i] and rev_word[end-i:] in words:
- pali_list.append((word, rev_word[end-i:]))
- if word[:i] == rev_word[end-i:] and rev_word[:end-i] in words:
- pali_list.append((rev_word[:end-i], word))
- end_time = time.time() # Getting the current time after finding palingrams
- print("\nNumber of palingrams = {}\n".format(len(pali_list))) # Printing the number of palingrams found
- print("Runtime for finding palingrams was {} seconds.".format(end_time - start_time)) # Printing the runtime
- save_option = input("\nDo you want to save the list of palingrams to a file? (y/n): ")
- if save_option.lower() == "y":
- save_to_file(pali_list) # Prompting the user to save the list if desired
- def save_to_file(pali_list):
- """Save list of palingrams to a file."""
- try:
- with open("palingrams_list.txt", "w", encoding="utf-8") as f:
- for palingram in pali_list:
- f.write("{} {}\n".format(palingram[0], palingram[1]))
- print("\nPalingrams list saved to 'palingrams_list.txt'.")
- except IOError as e:
- print("\nError saving palingrams list: {}".format(e))
- if __name__ == "__main__":
- find_palingrams() # Calling the find_palingrams function when the script is executed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement