Skip to content

Instantly share code, notes, and snippets.

@mkpoli
Created March 28, 2024 02:34
Show Gist options
  • Select an option

  • Save mkpoli/d75de5bb454bd00257b48192a6e14785 to your computer and use it in GitHub Desktop.

Select an option

Save mkpoli/d75de5bb454bd00257b48192a6e14785 to your computer and use it in GitHub Desktop.
Split ASS subtilte file by style
import regex as re
from pathlib import Path
TARGET_FILE = ".\YourFile.ass"
def split_ass_by_styles(file_path):
# Convert string path to Path object if not already
file_path = Path(file_path)
# Read ASS content from the file
with open(file_path, 'r', encoding='utf-8') as file:
ass_content = file.read()
# Splitting the content into header and events
header, events = ass_content.split('[Events]', 1)
header += '[Events]\n' # Add [Events] back to the header
# Finding all unique styles
style_pattern = re.compile(r'^Dialogue:.*?,.*?,.*?,(.*?),', re.MULTILINE)
styles = set(style_pattern.findall(events))
# Splitting and writing events for each style into separate files
for style in styles:
# Updated regex to correctly extract dialogues by style
filtered_events = re.findall(rf'^(Dialogue:.*?,.*?,.*?,{re.escape(style)},.*$)', events, re.MULTILINE)
file_content = header + '\n'.join(filtered_events)
output_file_path = file_path.with_stem(f'{file_path.stem}_{style}')
# Warning if the file exists
if output_file_path.exists():
print(f"Warning: {output_file_path} will be overwritten.")
with open(output_file_path, 'w', encoding='utf-8') as f:
f.write(file_content)
print("Files have been created/overwritten in the same directory as the input file.")
split_ass_by_styles(TARGET_FILE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment