格式字幕格式脚本

import os

import re

获取Python脚本所在的目录

directory = os.path.dirname(os.path.realpath(file))

遍历目录及其所有子目录下的所有文件

for root, dirs, files in os.walk(directory):

for filename in files:

如果文件是.srt文件

if filename.endswith('.srt'):

path = os.path.join(root, filename)

with open(path, 'r', encoding='utf-8') as file:

lines = file.readlines()

移除空白行

new_lines = [line for line in lines if not re.match(r'^\s*$', line)]

将处理过的行写回文件

with open(path, 'w', encoding='utf-8') as file:

file.writelines(new_lines)


import os

import re

def insert_blank_line(filename):

with open(filename, 'r', encoding='utf-8') as file:

lines = file.readlines()

new_lines = []

for line in lines:

if re.match(r'^[1-9]\d*', line.strip()):

new_lines.append('\n')

new_lines.append(line)

with open(filename, 'w', encoding='utf-8') as file:

file.writelines(new_lines)

def find_srt_files(path):

for root, dirs, files in os.walk(path):

for file in files:

if file.endswith('.srt'):

insert_blank_line(os.path.join(root, file))

if name == "main":

find_srt_files('.')

相关推荐
gis分享者2 天前
如何在 Shell 脚本中如何使用条件判断语句?(中等)
面试·shell·脚本·语法·使用·判断·条件
課代表6 天前
bat 批处理中的路径:%CD%与%~dp0
脚本·bat·环境变量·目录·批处理·路径·相对路径
世转神风-6 天前
windows-ps1脚本-获取网线直连下文件路径中的文件名
windows·脚本
世转神风-6 天前
ps1脚本-运行报错-并带有乱码
windows·脚本
課代表7 天前
bat 批处理从文本文件自动创建文件夹
自动化·脚本·bat·批处理·txt·文件编码·文件夹创建
gis分享者13 天前
如何在 Shell 脚本中使用管道(pipeline)实现数据传递?(容易)
linux·pipeline·shell·脚本·管道·数据传递
风123456789~13 天前
【Linux专栏】rsync实验-同步指定日期前的文件
linux·脚本·rsync
課代表21 天前
批处理脚本密码保护之简单加密
脚本·密码·批处理··加密算法·xor加密·密码复杂度
課代表1 个月前
批处理的应用与价值
系统·脚本·dos·变量·批处理·管道·办公
虚伪的空想家2 个月前
ip网段扫描机器shell脚本
android·linux·网络协议·tcp/ip·shell·脚本·network