本指南提供一個在Google Colab中運行的Python腳本,該腳本能夠讀取本機上的.srt字幕檔案,根據用戶指定的多個時段篩選字幕,刪除不需要的部分,並重新調整時間點。腳本支持中文、英文、日文等多語言字幕,並生成新的.srt檔案以供下載。
腳本支援UTF-8編碼,可處理多種語言的字幕,包括但不限於中文、英文、日文。這使得腳本適用於不同語言的影片內容,提升其使用範圍和靈活性。
用戶可以指定多個要保留的時段,腳本將僅保留這些時段內的字幕,並刪除其他不需要的部分。每個保留的時段將被單獨處理,確保字幕的時間點統一且連貫。
在刪除不需要的字幕後,腳本會自動重新調整保留字幕的起訖時間點,確保新的.srt檔案的時間軸連貫且邏輯一致。這對於編輯影片或僅保留特定內容的需求尤為重要。
首先,腳本需要導入處理文件、正則表達式以及日期時間的相關庫,以便進行後續的處理。
import re
from datetime import timedelta
from google.colab import files
腳本提供兩個函數,分別用於將時間碼轉換為毫秒,以及將毫秒轉換回標準的時間碼格式。
def time_to_ms(time_str):
"""將時間字串轉換為毫秒"""
hours, minutes, seconds_milliseconds = time_str.split(':')
seconds, milliseconds = seconds_milliseconds.split(',')
total_ms = (int(hours) * 3600000 + int(minutes) * 60000 + int(seconds) * 1000 + int(milliseconds))
return total_ms
def ms_to_time(ms):
"""將毫秒轉換為srt格式的時間字串"""
hours = ms // 3600000
ms %= 3600000
minutes = ms // 60000
ms %= 60000
seconds = ms // 1000
milliseconds = ms % 1000
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
透過正則表達式,腳本將.srt檔案內容分割為不同的字幕區塊,並提取每個字幕的序號、起訖時間及字幕文本。
def parse_srt(content):
"""解析srt內容並返回字幕列表"""
pattern = r'(\\d+)\\n(\\d{2}:\\d{2}:\\d{2},\\d{3}) --> (\\d{2}:\\d{2}:\\d{2},\\d{3})\\n(.*?)(?=\\n\\d+\\n|\\Z)'
subtitles = re.findall(pattern, content, re.DOTALL)
subtitle_list = []
for sub in subtitles:
index, start, end, text = sub
subtitle_list.append({
'index': int(index),
'start_ms': time_to_ms(start),
'end_ms': time_to_ms(end),
'text': text.strip()
})
return subtitle_list
用戶指定多個保留時段後,腳本將遍歷所有字幕,僅保留那些完全位於保留時段內的段落,並重新調整它們的時間點。
def filter_and_adjust_subtitles(subtitles, keep_ranges):
"""過濾字幕並調整時間"""
kept_subs = []
current_offset = 0
for range_start, range_end in keep_ranges:
range_start_ms = time_to_ms(range_start)
range_end_ms = time_to_ms(range_end)
for sub in subtitles:
if sub['start_ms'] >= range_start_ms and sub['end_ms'] <= range_end_ms:
new_start = sub['start_ms'] - range_start_ms + current_offset
new_end = sub['end_ms'] - range_start_ms + current_offset
kept_subs.append({
'index': len(kept_subs) + 1,
'start_ms': new_start,
'end_ms': new_end,
'text': sub['text']
})
current_offset += (range_end_ms - range_start_ms)
return kept_subs
根據處理後的字幕列表,腳本生成新的.srt內容,並依照標準格式保存。
def generate_new_srt(subtitles):
"""生成新的srt內容"""
srt_content = ""
for sub in subtitles:
srt_content += f"{sub['index']}\n"
srt_content += f"{ms_to_time(sub['start_ms'])} --> {ms_to_time(sub['end_ms'])}\n"
srt_content += f"{sub['text']}\n\n"
return srt_content
主函數負責從本機上傳.srt檔案,接收用戶輸入的保留時段,處理並生成新的字幕檔案,最後提供下載鏈接。
def main():
# 上傳srt檔案
print("請上傳.srt檔案")
uploaded = files.upload()
filename = list(uploaded.keys())[0]
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
# 解析原始字幕
subtitles = parse_srt(content)
# 輸入要保留的時段
print("\n請輸入要保留的時間範圍(格式:HH:MM:SS,mmm - HH:MM:SS,mmm)。輸入完成後輸入'done':")
keep_ranges = []
while True:
time_input = input()
if time_input.lower() == 'done':
break
try:
start, end = map(str.strip, time_input.split('-'))
keep_ranges.append((start, end))
except ValueError:
print("格式錯誤,請重新輸入。範例:00:02:15,000 - 00:02:40,000")
# 過濾並調整字幕
new_subtitles = filter_and_adjust_subtitles(subtitles, keep_ranges)
# 生成新的srt內容
new_content = generate_new_srt(new_subtitles)
# 儲存並下載新的srt檔案
new_filename = "output_" + filename
with open(new_filename, "w", encoding="utf-8") as f:
f.write(new_content)
files.download(new_filename)
if __name__ == "__main__":
main()
假設原始字幕檔案內容如下:
1
00:00:59,002 --> 00:01:01,202
AA
2
00:02:15,045 --> 00:02:17,045
BB
3
00:02:44,908 --> 00:02:47,744
CC
4
00:04:21,371 --> 00:04:24,671
DD
用戶選擇保留兩個時段「00:02:15,000 - 00:02:40,000」與「00:04:20,000 - 00:04:35,000」,腳本將生成以下新的.srt檔案:
1
00:00:00,045 --> 00:00:02,045
BB
2
00:00:26,371 --> 00:00:29,671
DD
在Google Colab中運行腳本,系統會提示您上傳一個.srt字幕檔案。選擇並上傳您需要處理的字幕檔案。
根據提示,輸入您想保留的字幕時段,格式為「HH:MM:SS,mmm - HH:MM:SS,mmm」。可以多次輸入多個時段,完成後輸入「done」來結束輸入。
腳本會根據您提供的保留時段篩選字幕,重新調整時間點,並生成一個新的.srt檔案。處理完成後,系統會自動下載新的檔案到您的本機。
import re
from datetime import timedelta
from google.colab import files
def time_to_ms(time_str):
"""將時間字串轉換為毫秒"""
hours, minutes, seconds_milliseconds = time_str.split(':')
seconds, milliseconds = seconds_milliseconds.split(',')
total_ms = (int(hours) * 3600000 + int(minutes) * 60000 + int(seconds) * 1000 + int(milliseconds))
return total_ms
def ms_to_time(ms):
"""將毫秒轉換為srt格式的時間字串"""
hours = ms // 3600000
ms %= 3600000
minutes = ms // 60000
ms %= 60000
seconds = ms // 1000
milliseconds = ms % 1000
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
def parse_srt(content):
"""解析srt內容並返回字幕列表"""
pattern = r'(\\d+)\\n(\\d{2}:\\d{2}:\\d{2},\\d{3}) --> (\\d{2}:\\d{2}:\\d{2},\\d{3})\\n(.*?)(?=\\n\\d+\\n|\\Z)'
subtitles = re.findall(pattern, content, re.DOTALL)
subtitle_list = []
for sub in subtitles:
index, start, end, text = sub
subtitle_list.append({
'index': int(index),
'start_ms': time_to_ms(start),
'end_ms': time_to_ms(end),
'text': text.strip()
})
return subtitle_list
def filter_and_adjust_subtitles(subtitles, keep_ranges):
"""過濾字幕並調整時間"""
kept_subs = []
current_offset = 0
for range_start, range_end in keep_ranges:
range_start_ms = time_to_ms(range_start)
range_end_ms = time_to_ms(range_end)
for sub in subtitles:
if sub['start_ms'] >= range_start_ms and sub['end_ms'] <= range_end_ms:
new_start = sub['start_ms'] - range_start_ms + current_offset
new_end = sub['end_ms'] - range_start_ms + current_offset
kept_subs.append({
'index': len(kept_subs) + 1,
'start_ms': new_start,
'end_ms': new_end,
'text': sub['text']
})
current_offset += (range_end_ms - range_start_ms)
return kept_subs
def generate_new_srt(subtitles):
"""生成新的srt內容"""
srt_content = ""
for sub in subtitles:
srt_content += f"{sub['index']}\n"
srt_content += f"{ms_to_time(sub['start_ms'])} --> {ms_to_time(sub['end_ms'])}\n"
srt_content += f"{sub['text']}\n\n"
return srt_content
def main():
# 上傳srt檔案
print("請上傳.srt檔案")
uploaded = files.upload()
filename = list(uploaded.keys())[0]
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
# 解析原始字幕
subtitles = parse_srt(content)
# 輸入要保留的時段
print("\n請輸入要保留的時間範圍(格式:HH:MM:SS,mmm - HH:MM:SS,mmm)。輸入完成後輸入'done':")
keep_ranges = []
while True:
time_input = input()
if time_input.lower() == 'done':
break
try:
start, end = map(str.strip, time_input.split('-'))
keep_ranges.append((start, end))
except ValueError:
print("格式錯誤,請重新輸入。範例:00:02:15,000 - 00:02:40,000")
# 過濾並調整字幕
new_subtitles = filter_and_adjust_subtitles(subtitles, keep_ranges)
# 生成新的srt內容
new_content = generate_new_srt(new_subtitles)
# 儲存並下載新的srt檔案
new_filename = "output_" + filename
with open(new_filename, "w", encoding="utf-8") as f:
f.write(new_content)
files.download(new_filename)
if __name__ == "__main__":
main()
本文詳細介紹了如何在Google Colab中使用Python腳本處理.srt字幕檔案。通過精確篩選多個保留時段、支持多語言字幕、以及自動調整時間點,該腳本為字幕編輯和影片內容精簡提供了一個高效、靈活的解決方案。無論是為特定片段添加字幕,還是清理不需要的內容,這個腳本都能滿足您的需求。