映画の字幕をダウンロードするとき、字幕ファイルがcd1.srtとcd2.srtに分割されているように見えることがよくありますが、映画は恥ずかしいものです。この問題を解決するために、私はそのような複数のファイルをマージする次のコードを書きました
字幕ファイルを読む
def read_srt(path):
content = ""
with open(path) as f:
content = f.read()
return content
小さなテスト
content = read_srt('1.srt')
print(content)
content = read_srt('2.srt')
print(content)
字幕をマージするには2つのポイントがあることがわかります。1つはコンテンツをマージする必要があること、もう1つは2.srtのシリアル番号も1から始まるため、シリアル番号を揃える必要があることです。
字幕分割
def get_sequences(content):
sequences = content.split('\n\n')
sequences = [sequence.split('\n') for sequence in sequences]
# 去除每一句空值
sequences = [list(filter(None, sequence)) for sequence in sequences]
# 去除整体空值
return list(filter(None, sequences))
小さなテスト
sequences = get_sequences(content)
sequences
字幕の変更
def change_sequences(sequences, start_index):
for sequence in sequences:
sequence[0] = str(start_index)
start_index += 1
新しい字幕を生成する
def save_srt(names):
new_content = []
start_index = 1
for name in names:
content = read_srt(name)
sequences = get_sequences(content)
change_sequences(sequences, start_index)
start_index = len(sequences) + 1
new_content += sequences
new_content = ['\n'.join(word) for word in new_content]
new_content = '\n\n'.join(new_content)
print(new_content)
with open('result.srt', 'a') as f:
f.write(new_content)
save_srt(['1.srt', '2.srt'])