SheridanCoriana6

subtitles split.py

Mar 28th, 2026
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.80 KB | Software | 0 0
  1. import os
  2. from tkinter import Tk, filedialog
  3. import re
  4. import chardet
  5.  
  6. def get_file_path():
  7.     """Displays a file dialog to select a file."""
  8.     root = Tk()
  9.     root.withdraw()
  10.     file_path = filedialog.askopenfilename(
  11.         title="Select a File",
  12.         filetypes=(
  13.             ("Text Files", "*.txt"),
  14.             ("All Files", "*.*")
  15.         )
  16.     )
  17.     return file_path
  18.  
  19. def get_max_words():
  20.     """Get maximum number of words per file from user"""
  21.     while True:
  22.         try:
  23.             max_words = int(input("Enter maximum number of words per file: "))
  24.             if max_words > 0:
  25.                 return max_words
  26.             print("Please enter a positive number.")
  27.         except ValueError:
  28.             print("Please enter a valid number.")
  29.  
  30. def count_words(text):
  31.     """Count words in text"""
  32.     return len(text.split())
  33.  
  34. def split_into_sentences(text):
  35.     """Split text into sentences while preserving original formatting"""
  36.     # Split by common sentence endings but preserve them in the result
  37.     sentences = []
  38.     current_sentence = ""
  39.    
  40.     for char in text:
  41.         current_sentence += char
  42.         # Check for sentence endings
  43.         if char in '.!?' and len(current_sentence.strip()) > 0:
  44.             # Look ahead for quotation marks or other ending characters
  45.             sentences.append(current_sentence)
  46.             current_sentence = ""
  47.    
  48.     # Add any remaining text as a sentence
  49.     if current_sentence:
  50.         sentences.append(current_sentence)
  51.    
  52.     return sentences
  53.  
  54. def detect_encoding(file_path):
  55.     """Detect the encoding of a file using chardet"""
  56.     with open(file_path, 'rb') as file:
  57.         raw_data = file.read()
  58.         result = chardet.detect(raw_data)
  59.         encoding = result['encoding']
  60.         confidence = result['confidence']
  61.         print(f"Detected encoding: {encoding} with confidence: {confidence:.2%}")
  62.         return encoding
  63.  
  64. def split_file(file_path, max_words):
  65.     try:
  66.         # Detect file encoding
  67.         encoding = detect_encoding(file_path)
  68.         if not encoding:
  69.             encoding = 'cp1250'  # Try with common Windows encoding for Polish
  70.             print(f"Could not detect encoding, trying with {encoding}")
  71.  
  72.         # Read file content with detected encoding
  73.         try:
  74.             with open(file_path, 'r', encoding=encoding) as file:
  75.                 content = file.read()
  76.         except UnicodeDecodeError:
  77.             # If still fails, try with cp1250 (common for Polish text files)
  78.             encoding = 'cp1250'
  79.             print(f"Failed with detected encoding, trying with {encoding}")
  80.             with open(file_path, 'r', encoding=encoding) as file:
  81.                 content = file.read()
  82.  
  83.         # Get file path info
  84.         directory, filename = os.path.split(file_path)
  85.         base_name, ext = os.path.splitext(filename)
  86.  
  87.         # Split into sentences
  88.         sentences = split_into_sentences(content)
  89.        
  90.         current_part = ""
  91.         current_words = 0
  92.         part_number = 1
  93.  
  94.         for sentence in sentences:
  95.             sentence_words = count_words(sentence)
  96.            
  97.             # If adding this sentence would exceed max_words and we already have content,
  98.             # save current part and start new one
  99.             if current_words + sentence_words > max_words and current_part:
  100.                 # Save current part
  101.                 output_file = f"{base_name}_part{part_number}{ext}"
  102.                 output_path = os.path.join(directory, output_file)
  103.                
  104.                 with open(output_path, 'w', encoding=encoding) as out_file:
  105.                     out_file.write(current_part)
  106.                
  107.                 # Start new part
  108.                 current_part = sentence
  109.                 current_words = sentence_words
  110.                 part_number += 1
  111.             else:
  112.                 # Add sentence to current part
  113.                 current_part += sentence
  114.                 current_words += sentence_words
  115.  
  116.         # Save last part if anything remains
  117.         if current_part:
  118.             output_file = f"{base_name}_part{part_number}{ext}"
  119.             output_path = os.path.join(directory, output_file)
  120.            
  121.             with open(output_path, 'w', encoding=encoding) as out_file:
  122.                 out_file.write(current_part)
  123.  
  124.         print(f"File split into {part_number} parts successfully.")
  125.         print(f"Encoding used: {encoding}")
  126.         print("Note: Some parts might slightly exceed the word limit to preserve complete sentences.")
  127.  
  128.     except Exception as e:
  129.         print(f"An error occurred: {e}")
  130.  
  131. if __name__ == "__main__":
  132.     file_path = get_file_path()
  133.     if file_path:
  134.         max_words = get_max_words()
  135.         split_file(file_path, max_words)
  136.     else:
  137.         print("No file selected. Exiting.")
Advertisement
Add Comment
Please, Sign In to add comment