Ruby/Rails text parse into objects -
i'm trying create objects each recurring set in text below (an .srt subtitle file):
1 00:02:12,446 --> 00:02:14,406 hovitos near. 2 00:02:15,740 --> 00:02:18,076 poison still fresh, 3 days. 3 00:02:18,076 --> 00:02:19,744 they're following us.
for example, take 3 or 4 lines , assign them attributes of new object. first set, have sentence.create(number: 1, time_marker: '00:02:12', content: "the hovitos near.")
start script.each_line
, , other general structure might put me on right track? i'm having hard time , fantastic!
edit
some of messy unfinished code have far below. works (i think). have taken totally different route? don't have experience this.
number = nil time_marker = nil content = [] script = script.strip script.each_line |line| line = line.strip if line =~ /^\d+$/ number = line.to_i elsif line =~ /-->/ time_marker = line[0..7] elsif line =~ /^\b\d/ content << line else if content.size > 1 content = content.join("\n") else content = content[0] end sentence.create(movie: @movie, number: number, time_marker: time_marker, content: content) content = [] end end
here way can it:
file.read('subtitles.srt').split(/^\s*$/).each |entry| # read in entire text , split on empty lines sentence = entry.strip.split("\n") number = sentence[0] # first element after empty line 'number' time_marker = sentence[1][0..7] # second element 'time_marker' content = sentence[2..-1].join("\n") # after 'content' end
Comments
Post a Comment