secret
anonymous / JacobLichner
Last active

Jacob Lichner Solution

  • Download Gist
JacobLichner
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#! /usr/local/bin/ruby
 
#
# RPCFN #1 from RubyLearning:
# http://rubylearning.com/blog/2009/09/24/rpcfn-shift-subtitle-1/
#
# Challenge Summary:
# Shift the subtitle time intervals of an SRT file.
#
 
require 'optparse'
require 'time'
 
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: shift_subtitles.rb [options] input_file output_file"
opts.on('-o', '--operation OPERATION', [:add,:sub], 'Shift subtitles forward (use "add") or backward (use "sub").') do |operation|
options[:operation] = operation
end
opts.on('-t','--time TIME', 'Seconds and milliseconds to shift subtitles (example: 02,500).') do |time|
options[:time] = time.gsub(',', '.').to_f
end
opts.on('-h', '--help', 'Display this screen.') do
puts opts
exit
end
 
opts.parse!
end
 
def format_time time
time.strftime('%H:%M:%S') + ',' + time.usec.to_s.chomp('000')
end
 
def new_times time1, time2
format_time(time1) + ' --> ' + format_time(time2) + "\n"
end
 
def shift_time current_time, operation, time
if operation == :add
current_time + time
elsif operation == :sub
current_time - time
end
end
 
input_file = ARGV[0]
output_file = ARGV[1]
 
output = File.readlines(input_file).map do |line|
if line.match(/\d\d:\d\d:\d\d,\d\d\d\s-->\s\d\d:\d\d:\d\d,\d\d\d/)
times = line.chomp.split(' --> ').map { |time| shift_time(Time.parse(time), options[:operation], options[:time]) }
line = new_times(times[0], times[1])
else
line = line
end
end
 
File.open(output_file, 'w') { |file| file.write(output.to_s) }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.