Advertisement
Python253

ipp4_0_single_anagrams

May 31st, 2024
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.63 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: ipp4_0_single_anagrams.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script demonstrates "Chapter 3: Project #4 - Single Anagrams" from the book "Impractical Python Projects" by Lee Vaughan.
  10.    - This script allows users to find single word anagrams of a given word by searching a dictionary file.
  11.    - It downloads a dictionary file from a specified URL, loads it into memory, and then searches for anagrams of the user-provided word within the dictionary.
  12.    
  13. Requirements:
  14.    - Python 3.x
  15.    - The following modules:
  16.        - sys
  17.        - requests
  18.  
  19. Functions:
  20.    - download_dictionary(url, file_name):
  21.        - Description:
  22.            - Downloads a dictionary file from a 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.        - Raises:
  27.            - requests.RequestException: If an error occurs during the HTTP request.
  28.        
  29.    - load_dictionary(file):
  30.        - Description:
  31.            - Opens a text file and turns its contents into a list of lowercase strings.
  32.        - Parameters:
  33.            - file (str): The name of the file to open.
  34.        - Returns:
  35.            - list: A list of lowercase strings containing the words from the file.
  36.    
  37.    - find_anagrams(word, word_list):
  38.        - Description:
  39.            - Finds anagrams of a given word in a list of words.
  40.        - Parameters:
  41.            - word (str): The word to find anagrams for.
  42.            - word_list (list): A list of words to search for anagrams.
  43.        - Returns:
  44.            - list: A list of anagrams found in the word list.
  45.    
  46. Usage:
  47.    - Ensure you have Python 3.x installed on your system.
  48.    - Save the script to a file, for example, `anagrams.py`.
  49.    - Run the script using the command: python anagrams.py.
  50.  
  51. Example Output:
  52.    Enter a word to find its anagrams: sample
  53.    Anagrams of 'sample':
  54.    maples
  55.  
  56. Additional Notes:
  57.    - The dictionary file is downloaded from the specified URL. Ensure an active internet connection for successful download.
  58.    - Anagrams are case-insensitive.
  59. """
  60.  
  61. import sys
  62. import requests
  63.  
  64. def download_dictionary(url, file_name):
  65.     """
  66.    Download a dictionary file from a URL.
  67.    
  68.    Parameters:
  69.        url (str): The URL from which to download the dictionary file.
  70.        file_name (str): The name to save the downloaded file as.
  71.    
  72.    Raises:
  73.        requests.RequestException: If an error occurs during the HTTP request.
  74.    """
  75.     try:
  76.         response = requests.get(url)
  77.         with open(file_name, 'wb') as f:
  78.             f.write(response.content)
  79.     except requests.RequestException as e:
  80.         print("Error downloading dictionary from {}: {}".format(url, e))
  81.         sys.exit(1)
  82.  
  83. def load_dictionary(file):
  84.     """
  85.    Open a text file & turn contents into a list of lowercase strings.
  86.    
  87.    Parameters:
  88.        file (str): The name of the file to open.
  89.    
  90.    Returns:
  91.        list: A list of lowercase strings containing the words from the file.
  92.    """
  93.     try:
  94.         with open(file, encoding='utf-8') as in_file:
  95.             loaded_txt = in_file.read().strip().split('\n')
  96.             loaded_txt = [x.lower() for x in loaded_txt]
  97.             return loaded_txt
  98.     except IOError as e:
  99.         print("{}\nError opening {}. Terminating program.".format(e, file))
  100.         sys.exit(1)
  101.  
  102. def find_anagrams(word, word_list):
  103.     """
  104.    Find anagrams of a given word in a list of words.
  105.    
  106.    Parameters:
  107.        word (str): The word to find anagrams for.
  108.        word_list (list): A list of words to search for anagrams.
  109.    
  110.    Returns:
  111.        list: A list of anagrams found in the word list.
  112.    """
  113.     word_sorted = sorted(word.lower())
  114.     anagrams = [w for w in word_list if sorted(w) == word_sorted and w.lower() != word.lower()]
  115.     return anagrams
  116.  
  117. def main():
  118.     dictionary_url = "https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt"
  119.     dictionary_file = "dictionary.txt"
  120.     download_dictionary(dictionary_url, dictionary_file)
  121.    
  122.     user_input = input("Enter a word to find its anagrams: ").strip()
  123.    
  124.     word_list = load_dictionary(dictionary_file)
  125.     anagrams = find_anagrams(user_input, word_list)
  126.    
  127.     if anagrams:
  128.         print("Anagrams of '{}':".format(user_input))
  129.         for anagram in anagrams:
  130.             print(anagram)
  131.     else:
  132.         print("No anagrams found in dictionary for '{}'.".format(user_input))
  133.  
  134. if __name__ == "__main__":
  135.     main()
  136.  
  137.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement