Chinaunix首页 | 论坛 | 博客
  • 博客访问: 56858
  • 博文数量: 12
  • 博客积分: 1480
  • 博客等级: 上尉
  • 技术积分: 240
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-20 10:01
文章分类
文章存档

2010年(1)

2008年(11)

我的朋友
最近访客

分类:

2010-01-20 00:29:29

(折腾了半天也没搞定如何在百度空间里保留代码的格式,所以还是贴在这里备忘好了)

前几天晚上看电影时,发现两个avi格式的文件对应的中文字幕居然只有一个文件,当开始看cd2的时候,中文字幕还是cd1的,而且找遍了播放器也没办法调整时间轴。
打开字幕文件一看,格式很简单,但是手动调整则几乎是不可能的,于是就打算写个小脚本处理一下。
在windows下,shell就不考虑了,最后打算用perl。折腾了一个多小时终于搞定了。其中关于时间相减的子过程以前写过却不在手头上,只得从头又写了一遍,所以为了以后不必再次重复,打算将这个脚本放在网上供以后参考之。

用法:script.pl <字幕文件名>
如: script hello.srt 1:13:45 , 则会生成两个文件,分别为:hello-a.srt, hello-b.srt

代码如下:


#!/usr/bin/perl -w

#
# a script to plit a subtitle file into two files, split at a certain time.
#
# Chunis Deng (chunchengfh@gmail.com)
#

use strict;
use warnings;

# substract two times
# sub_time("35:25", "29:44") or sub_time("21:35:25", "12:29:44")
# sub_time("2:34:45", "37:22") will fail

sub sub_time {
    my ($x, $y) = @_;
    my ($i, @x, @y);
    @x = split /:/, $x;
    @y = split /:/, $y;
  
    die "Error! '$x' and '$y' have different time format.\n" if $#x != $#y;
  
    for($i=0; $i<=$#x; $i++){
        $x[$i] -= $y[$i];
    }
    for($i=$#x; $i>0; $i--){
        if($x[$i] < 0){
            $x[$i] += 60;
            $x[$i-1] -= 1;
        }
    }
  
    #join ":", @x;
    sprintf "%02d:%02d:%02d", @x;
}

# test sub_time()
# my $m = "03:25:07";
# my $n = "01:38:56";
# my $s = sub_time($m, $n);
# print "$m - $n = $s\n";

my ($file, $ct, $n, $is_part1);
$n = 1; # messages count flag
$is_part1 = 1; # $is_part1 == 1 means we haven't reach to the second part yet

$#ARGV >= 1 || die "Usage:\n\t$0 subtitle_file substract_time\n";

$file = shift @ARGV;
$ct = shift @ARGV;

my ($file_a, $file_b);
$file =~ /([^.]*)(\.?.*)/;
$file_a = $1 . "-a" . $2;
$file_b = $1 . "-b" . $2;

open FILE, "<", $file
    or die "open subtitle file '$file' failed: $!";
open F1, ">", $file_a
    or die "open subtitle file '$file' failed: $!";
open F2, ">", $file_b
    or die "open subtitle file '$file' failed: $!";
print F2 "1\n";

while(my $line = <FILE>){
    chomp $line;
    if($line =~ /^(\d+)$/){
        if($is_part1){ # we are still in the 1st part
            $n = $1;
        } else { # we reach to the 2nd part now
            $line = $1 - $n + 1;
        }
    } elsif($line eq ""){
        1;
    } elsif($line =~ /--/){
        my ($t1, $t2) = (split /[, ]/, $line)[0, 3];
        $t1 = sub_time($t1, $ct);
        $t2 = sub_time($t2, $ct);
        if($t1 =~ /^\d/){ # $t1 is later than $ct now(the 2nd argument)
            $is_part1 = 0;
            $line =~ s/^.*(,.* )[\d:]+(,.*)$/$t1$1$t2$2/;
        }
    }
  
    if($is_part1){
        print F1 "$line\n";
    } else {
        print F2 "$line\n";
    }
}


阅读(772) | 评论(0) | 转发(0) |
0

上一篇:Play with JOS (0x14): JOS内存使用(2)

下一篇:没有了

给主人留下些什么吧!~~