Write a program that reads words from a filename, which is given as a string argument. It should return the words from the file in a list, sorted in reverse alphabetical order (case insensitive) . For instance, if the file has bell tea Zebra apple yellow Then the output should be ['Zebra', 'yellow', 'tea', 'bell', 'apple'] def reverse_sorted_words(filename): # YOUR CODE HERE raise NotImplementedError()
Write a program that reads words from a filename, which is given as a string argument. It should return the words from the file in a list, sorted in reverse alphabetical order (case insensitive) .
For instance, if the file has
bell tea Zebra apple yellow
Then the output should be
['Zebra', 'yellow', 'tea', 'bell', 'apple']
def reverse_sorted_words(filename):
# YOUR CODE HERE
raise NotImplementedError()
Input:
- A string `filename` representing the path to the input file.
Output:
- A list of words sorted in reverse alphabetical order (case insensitive).
1. Define a function `reverse_sorted_words(filename)`:
1.1. Use a `try...except` block to handle potential errors:
1.1.1. If a `FileNotFoundError` occurs, print a message indicating that the file was not found.
1.1.2. If any other exceptions occur, print an error message.
1.2. Inside the `try` block:
1.2.1. Open the file specified by `filename` in read mode using a `with` statement.
1.2.2. Read the content of the file and store it in a variable named `content`.
1.2.3. Split the `content` into individual words and store them in a list named `words`.
1.3. Sort the `words` list in reverse alphabetical order (case insensitive):
1.3.1. Use the `sorted` function with a custom `key` function that converts each word to lowercase for case-insensitive sorting.
1.3.2. Use the `reverse` parameter to sort the words in reverse order (from 'Z' to 'A').
1.4. Return the `sorted_words` list.
2. In case of any exceptions (e.g., `FileNotFoundError` or general exceptions), handle the errors by printing appropriate messages to the console.
3. Provide an example usage of the function:
3.1. Specify the desired filename (replace `"your_file.txt"` with the actual file path).
3.2. Call the `reverse_sorted_words` function with the filename as an argument.
4. If the function execution is successful:
4.1. Print the `sorted_words` list, which contains words sorted in reverse alphabetical order (case insensitive).
5. End the program.
Step by step
Solved in 4 steps with 3 images