格式字幕格式脚本

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('.')

相关推荐
Thanks_ks17 天前
【第 008 讲】在终端中运行 Python 程序:交互模式与脚本模式 | 绝对路径与相对路径 | 以模块方式运行 | 常见报错的识别与排查
python·异常处理·终端·脚本·命令行·cmd·python 解释器
谙弆悕博士18 天前
在文件夹右键直接打开 Kali WSL:一条 `wsl --cd` 注册表脚本
windows·脚本·wsl·右击·ksli
Shell运维手记1 个月前
Shell 结构化命令知识点总结(case、for、while)
运维·microsoft·shell·脚本
PegasusYu2 个月前
Node.js使用nedb轻量级数据库测试脚本
数据库·electron·node.js·脚本·测试·轻量级·nedb
东鹏特饮2 个月前
15个实用Linux运维脚本
linux·运维·shell·脚本·redhat·常用生产脚本
Hello_Pyhx2 个月前
MAA 首次连接模拟器:从 ADB 配置到单项任务验证
自动化·脚本·明日方舟
青柠之夏cc2 个月前
掌握自动化,高效工作新引擎
编程·脚本·语法
k4m7v2pz2 个月前
ThinkPad E490 风扇 “转两秒就停“ 实录:迟滞曲线 + 最短运转时间
linux·脚本·archlinux·thinkpad·风扇·散热
五_谷_丰_登2 个月前
cmake脚本学习——持续更新
脚本·cmake
szephyr2 个月前
用 Python 写自动化脚本:定时任务、文件批处理、自动出报表
python·自动化·pandas·脚本·定时任务