python学习

python学习

正则表达式的使用

正则表达式

以下是替换指定文件夹下文本中的内容
对图片形式的pdf提取目录,可以用以下程序叠加多个正则表达式来去除重复项。

import os
import re

def replace_timestamp(directory):
    # 遍历目录下的所有文件和文件夹
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".srt"):
                file_path = os.path.join(root, file)

                # 打开文件并读取内容
                with open(file_path, "r",encoding='UTF-8') as f:
                    content = f.read()

                # 使用正则表达式替换时间戳
                replaced_content = re.sub(r"([\d]+\n)([\d:]+)(,[\d:]+) --> ([\d+:]+)(,[\d]+)\n", r"[\2]  ", content)
                # replaced_content = re.sub(r"([\d]+\n)", r"[\1]  ", content)

                # 将替换后的内容写回文件
                with open(file_path, "w",encoding='UTF-8') as f:
                    f.write(replaced_content)

# 指定目录路径
directory = "D:\\subtitle_copy"

# 调用函数进行替换
replace_timestamp(directory)


posted @ 2023-09-03 11:13  聚之  阅读(27)  评论(0)    收藏  举报