Advertisement
Python253

mixed_list_sorter

May 20th, 2024
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.43 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: mixed_list_sorter.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. :: Mixed List Sorter ::
  9.  
  10. Description:
  11.    This script sorts a mixed list of words and numerical strings in alphanumerical order and saves the sorted content to a new file.
  12.  
  13. Requirements:
  14.    - Python 3.x
  15.    - tkinter library (for file dialog)
  16.  
  17. Functions:
  18.    - select_file(): Opens the file manager in the current working directory and lets the user select the file to sort.
  19.    - sort_file(input_file_path): Sorts the lines of the input file in alphanumerical order and saves the sorted content to a new file.
  20.  
  21. Usage:
  22.    1. Run the script.
  23.    2. The file manager will open, allowing you to select a text file to sort.
  24.    3. After selecting the file, the script will sort the content and save the sorted content to a new file named "sorted_list.txt" in the same directory as the original file.
  25.  
  26. Additional Notes:
  27.    - The script can handle both words and numerical strings mixed together in the input file.
  28.    - The sorted content is saved with headers indicating the sorted number list and the sorted word list in the output file.
  29. """
  30.  
  31. # Get Essential Imports
  32. import os
  33. from tkinter import filedialog
  34.  
  35. # Function to get user selected file to sort
  36. def select_file():
  37.     """
  38.    Open the file manager in the current working directory and let the user select the file to sort.
  39.  
  40.    Returns:
  41.        str: The selected file path.
  42.    """
  43.     cwd = os.getcwd()
  44.     file_path = filedialog.askopenfilename(
  45.         initialdir=cwd,
  46.         title="Select file",
  47.         filetypes=(("Text files", "*.txt"), ("All files", "*.*")),
  48.     )
  49.     return file_path
  50.  
  51. # Function to sort the selected file in alphanumerical order
  52. def sort_file(input_file_path):
  53.     """
  54.    Sort the lines of the input file in alphanumerical order and save the sorted content to a new file.
  55.  
  56.    Args:
  57.        input_file_path (str): The path of the input file to be sorted.
  58.    """
  59.     try:
  60.         with open(input_file_path, "r", encoding="utf-8") as file:
  61.             lines = file.readlines()
  62.  
  63.         # Separate lines into numbers and letters
  64.         numbers = [line.strip() for line in lines if line.strip().isdigit()]
  65.         letters = [line.strip() for line in lines if not line.strip().isdigit()]
  66.  
  67.         # Sort numbers and letters separately
  68.         numbers.sort(key=int)
  69.         letters.sort()
  70.  
  71.         # Merge sorted numbers and letters with headers
  72.         sorted_lines = (
  73.             ["Sorted number list:\n"] + numbers + ["", "Sorted word list:\n"] + letters
  74.         )
  75.  
  76.         # Dynamically name the output file based on the input fil name
  77.         base_name = os.path.basename(input_file_path)
  78.         dir_name = os.path.dirname(input_file_path)
  79.         output_file_path = os.path.join(dir_name, f"sorted_{base_name}")
  80.  
  81.         with open(output_file_path, "w", encoding="utf-8") as file:
  82.             file.write("\n".join(sorted_lines))
  83.  
  84.         print(f"File '{input_file_path}'\nHas been sorted successfully.")
  85.         print(f"\nSorted content has been written to:\n'{output_file_path}'.")
  86.  
  87.     except Exception as e:
  88.         print(f"\nAn error occurred: {e}\n")
  89.  
  90. def main():
  91.     """
  92.    Main function to run the script.
  93.    """
  94.     selected_file = select_file()
  95.     if selected_file:
  96.         sort_file(selected_file)
  97.     else:
  98.         print("\nNo file selected!\n")
  99.  
  100. if __name__ == "__main__":
  101.     main()
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement