Python生成双语字幕文件

过了九月以后就是美剧爆发的季节,等有字幕的RMVB(我承认我对画质的要求下降了。。。)已经跟不上进度。遂又开始了每周去eztv下载avi然后去射手搜字幕的时候。

字幕这个事呢,不能强求。有些字幕组会做中英文合并的单字幕文件,有些呢,就是中英文分开的两个。对于俺这种喜欢看双语字幕的人,就需要多做一步。以前都是人肉操作,现在改脚本帮忙了。

目标:把两种语言的两个字幕文件(比如.cn.srt文件和.en.srt文件)合并为一个单独的双语字幕文件(比如.combined.srt)

思路:想必大家都知道,把中、英文2个字幕文件中的任一个的内容加到另一个文件中保存后,那个合并过的srt文件就是双语字幕了。

脚本说明:非常的简单,就是读一个文件然后写入另一个。我懒得想复杂的功能了,以下代码可以成功执行的情况:

  • 把代码保存为.py文件,放到希望整合srt的目录
  • 该目录下有且只有2个.srt文件
  • 文件名以.combined.srt结尾的文件就是咱们需要的了

脚本源码:

#coding=utf-8
from __future__ import unicode_literals
import os

srtFiles= [ i for i in os.listdir(os.getcwd()) if i.endswith('.srt')]
srtFiles.sort()
assert len(srtFiles) ==2
with open(srtFiles[0],'r') as f1:
    with open(srtFiles[1],'a') as f2:
        f2.writelines(f1.readlines())
os.rename(srtFiles[1],os.path.splitext(srtFiles[1])[0] +'.combined.srt')

Python版图片合成脚本

Oct/13/2011 update script: remove urgly lambda, use os.path.splitext()

之前写过用Ruby+ImageMagick整合多张图片,因为现在转用python,所以又用python写了一个。

当然,这个脚本的前提也是需要安装ImageMagick,而且要把它的bin目录加到PATH里面。也就是说在命令行下面输入montage不会提示找不到程序。另外,你还要装Python环境。。。

这次写的Python版比较简单,没有写Usage,这里提一下:

把脚本文件搁到你要整合图片的目录,然后执行脚本。该目录所有图片就合成一个叫result.png的文件了。

运行时会提示用哪种方式连接。默认的是普通的拼接。那个photostyle是相册风格的,具体的自己试下就行了。

代码如下:

import os
imgTypes=('.jpg','jpeg','.png','.gif')
#isImg= lambda x: x.find('.') >0 and x.split('.')[1] in imgTypes
#imgFiles=[f for f in os.listdir(os.getcwd()) if isImg(f) and f.find('result') < 0]
imgFiles=[f for f in os.listdir(os.getcwd()) if os.path.splitext(f)[1].lower() in imgTypes and f.find('result') < 0]
imgStrings=reduce(lambda x,y: '%s %s'%(x,y), imgFiles)

photoStyle='montage %s -auto-orient -bordercolor Lavender -background white +polaroid -tile 1x -gravity center -background SkyBlue  -geometry "1x1<" result.jpg'%imgStrings
plainStyle='montage %s -tile 1x -geometry "1x1<" result.jpg'%imgStrings
choice=raw_input("1. default: plain\t2. photo style\nplz choose image merge type:")
if choice == '' or choice == '1':
    os.system(plainStyle)
else:
    os.system(photoStyle)

样图:

PhotoStyle:               PlainStyle:

otostyleotostyle