perl正则表达式,文件读取常用方法

前端之家收集整理的这篇文章主要介绍了perl正则表达式,文件读取常用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好久没有写perl脚本了,最近电脑上面有《prison break》的音频,也有srt的歌词,不过歌词不对,最后进行下面的脚本处理后,可以变听变看字幕了。

主要是用来复习下perl脚本,正则表达式,文件读取,循环,条件等

#! /usr/bin/perl 
#print 'done';
# my $file = '<E:\Prison Break1\Prison Break - 1x02 - Allen [eng-subtitle].srt';
# my $out  = '>E:\Prison Break1\P02.srt';

# open(FILE,$file) or die "$!\n";
# open(RESULT,$out) or die $!;

my $dirMp3AndLrc = 'E:\Prison Break1';	#MP3,lrc文件都在此文件夹中,
my $dirLrcTarget = 'E:\PB';

opendir(MP3_AND_LRC,$dirMp3AndLrc) or die $!;
my @mp3;	#mp3格式
my @lrc;	#lrc格式
my $hashMp3;
my $hashLrc;


while($file = readdir(MP3_AND_LRC)) {
	# $i = 0;
	if ($file =~ /\.srt$/) {
		# push @lrc,$file;
		# print $file . "\n";
		my $lyric = "<$dirMp3AndLrc\\$file";
		open(SRT,$lyric) or die "$!\n";
		open(RESULT,">$dirLrcTarget\\$file") or die "$!\n";
		# print ">$dirMp3\\$file\n";
		my $li;
		my @final;
		my @lines = <SRT>;
		for(my $i=0; $i<@lines; $i++) {
			$line = $lines[$i];
			# # print 'before: i=' . $i . '; v=' . $line;#. "\n";
			# $li .= $li2;
				# # print 'after: i=' . $i . '; v=' . $line;#. "\n";
			# $line =~ s/[\r\n]//;
			if ($line =~ /(^\d)/ or $line =~ /(^$)/s){
				# @final[] = $line;
				# print "tag\n";
				push @final,$line;
			} else {
				# print "real=\n";
				my $realWords = '';
				my $tmp;
				for ($tmp = 0; $tmp<@lines; $tmp++) {
					# print 't=' . $tmp . "\n";
					# print 'v=' .$lines[$i+$tmp] . "\n";
					if ($lines[$i+$tmp] =~ /(^\d)/ or $lines[$i+$tmp] =~ /(^$)/s){
						last;
					} else {
						$realWords .= $lines[$i+$tmp];
					}
				}
				$i += $tmp;
				$realWords =~ s/\n/ /g;
				push @final,$realWords . "\n\n";
				print 'realWords=' . $realWords . "\n";
			}
		}
		# print 'line=' . $li;

		print RESULT @final;
		close(SRT);
		close(RESULT);
	}
}

# foreach(@lrc) {
	# $name = $_;
	# $list = substr($name,17,2);
	# $list =~ s/^0//;
	# $name =~ s/\.srt$//;
	# rename "$dir\\$list.mp3","$dir\\$name.mp3";  
	# print "before modify: $dir\\$list.mp3,\n\nafter modify: $dir\\$name.mp3\n";
# } 

closedir PB;

exit;



猜你在找的Perl相关文章