Created
September 18, 2017 06:18
-
-
Save zapstar/6ae0784f3e0b13df6deca35e53569740 to your computer and use it in GitHub Desktop.
Rename the videos downloaded from CS161 - Tim Roughgarden
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# CS 161 - Design and Analysis of Algorithms - Tim Roughgarden | |
# | |
# Script to rename FLV files using their XML containing metadata. | |
# I personally prefer the blackboard videos, so wrote a script to rename the | |
# videos to have proper titles. | |
# | |
# This is a script that gets job done, not something you'd want to integrate | |
# into some production code, so use it at your own risk. | |
# | |
# NOTE: Keep a copy of all the FLV files, just in case :-) | |
# | |
# Link to web page: | |
# http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=IntroToAlgorithms | |
# | |
# Link to XML and FLV files: | |
# http://openclassroom.stanford.edu/MainFolder/courses/IntroToAlgorithms/videos/ | |
import os | |
import re | |
import string | |
import xml.etree.ElementTree | |
def get_title_and_file(xml_file_name): | |
# Crappy, but gets the work done ... | |
root = xml.etree.ElementTree.parse(xml_file_name).getroot() | |
title = "" | |
video_file = "" | |
for child in root: | |
if child.tag == "title": | |
title = child.text | |
elif child.tag == "videoFile": | |
video_file = child.text | |
if title == "" or video_file == "": | |
raise ValueError("Invalid XML file %s passed" % xml_file_name) | |
return title, video_file | |
def extract_lno_pno(file_name): | |
p = re.compile("CS161L(\d+)P(\d+)\w?\.flv") | |
m = p.match(file_name) | |
if m is None: | |
raise ValueError("Filename %s is not properly formatted" % file_name) | |
return int(m.group(1)), int(m.group(2)) | |
def gen_file_name(title, file_name): | |
lno, pno = extract_lno_pno(file_name) | |
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) | |
valid_title = ''.join(c for c in title if c in valid_chars) | |
return '%02d - %02d - %s.flv' % (lno, pno, valid_title) | |
def rename_file(xml_file_name): | |
title, old_name = get_title_and_file(xml_file_name) | |
new_name = gen_file_name(title, old_name) | |
print "Renaming file '%s' to '%s'" % (old_name, new_name) | |
os.rename(old_name, new_name) | |
if __name__ == "__main__": | |
for filename in os.listdir("."): | |
if filename.endswith(".xml"): | |
try: | |
rename_file(filename) | |
except ValueError, e: | |
print "Error: " + str(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment