WangShuXian6 / blog

FE-BLOG
https://wangshuxian6.github.io/blog/
MIT License
46 stars 10 forks source link

Python 代码片段 #190

Open WangShuXian6 opened 6 months ago

WangShuXian6 commented 6 months ago

Python 代码片段

WangShuXian6 commented 5 months ago

根据旧,新名称批量重命名

旧,新 文件名默认以逗号分隔,也可以自定义分隔符例如$$$ 文件名需要带后缀名:1.mp4$$$a.mp4

python

import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import os

class FileRenamerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("文件重命名工具")

        # 旧名称-新名称映射的输入框
        tk.Label(root, text="输入文件名映射(旧名,新名):").pack(pady=10)
        self.text = scrolledtext.ScrolledText(root, height=15, width=60)
        self.text.pack()

        # 自定义分隔符输入框
        tk.Label(root, text="自定义分隔符(默认为逗号):").pack(pady=10)
        self.separator = tk.StringVar(value=',')
        tk.Entry(root, textvariable=self.separator, width=5).pack(pady=5)

        # 选择目录的按钮
        self.folder_path = tk.StringVar()
        tk.Label(root, text="选择目录:").pack(pady=10)
        tk.Entry(root, textvariable=self.folder_path, width=50).pack(pady=5)
        tk.Button(root, text="浏览", command=self.browse_directory).pack()

        # 重命名文件的按钮
        tk.Button(root, text="重命名文件", command=self.rename_files).pack(pady=20)

    def browse_directory(self):
        """ 打开文件对话框选择目录 """
        folder_selected = filedialog.askdirectory()
        if folder_selected:
            self.folder_path.set(folder_selected)

    def rename_files(self):
        """ 重命名选定目录中的文件 """
        directory = self.folder_path.get()
        if not os.path.isdir(directory):
            messagebox.showerror("错误", "请选择有效的目录")
            return

        # 从文本框中读取文件映射
        separator = self.separator.get()
        mappings = self.text.get("1.0", tk.END).strip().split("\n")
        file_mappings = {}
        for mapping in mappings:
            if separator in mapping:
                old_name, new_name = mapping.split(separator, 1)
                file_mappings[old_name.strip()] = new_name.strip()

        # 重命名文件
        success_files = []
        not_found_files = []
        for old_name, new_name in file_mappings.items():
            old_file = os.path.join(directory, old_name)
            new_file = os.path.join(directory, new_name)
            if os.path.exists(old_file):
                os.rename(old_file, new_file)
                success_files.append(f"{old_name} -> {new_name}")
            else:
                not_found_files.append(old_name)

        # 显示结果
        result_message = "重命名完成!\n\n"
        if success_files:
            result_message += "成功重命名的文件:\n" + "\n".join(success_files) + "\n\n"
        if not_found_files:
            result_message += "未找到的文件:\n" + "\n".join(not_found_files)
        messagebox.showinfo("结果", result_message)

if __name__ == "__main__":
    root = tk.Tk()
    app = FileRenamerApp(root)
    root.mainloop()

输入的名称格式为:

旧文件名1,新文件名1 旧文件名2,新文件名2

以换行分隔多组文件名,带文件格式后缀 示例

009 Social Media Design Niche.mp4,009 社交媒体设计利基.mp4  
010 Student Project.mp4,010 学生项目.mp4

输入的名称格式为:

旧文件名1$$$新文件名1 旧文件名2$$$新文件名2

以换行分隔多组文件名,带文件格式后缀 示例

009 Social Media Design Niche.mp4$$$009 社交媒体设计利基.mp4  
010 Student Project.mp4$$$010 学生项目.mp4

图片

使用js脚本一次获取指定目录下的mp4文件名称【也包含子目录下的mp4】

listsort.js


const fs = require('fs').promises;
const path = require('path');

// 获取当前目录 const currentDir = process.cwd();

// 辅助函数,用于提取文件或目录名的数字前缀 function extractNumber(prefix) { const match = prefix.match(/^\d+/); return match ? parseInt(match[0], 10) : null; }

// 主函数,列出并排序目录及其文件 async function listFiles(dirPath) { try { const entries = await fs.readdir(dirPath, { withFileTypes: true }); // 过滤并排序目录,不包含普通话chatgpt3.5turbo const directories = entries .filter(entry => entry.isDirectory() && entry.name !== '普通话chatgpt3.5turbo') .sort((a, b) => extractNumber(a.name) - extractNumber(b.name));

    for (const dir of directories) {
        console.log(dir.name); // 打印目录名称

        const files = await fs.readdir(path.join(dirPath, dir.name));
        const mp4Files = files
            .filter(file => path.extname(file).toLowerCase() === '.mp4')
            .sort((a, b) => extractNumber(a) - extractNumber(b));  // 根据数字排序文件名

        mp4Files.forEach(file => console.log(file)); // 打印.mp4文件名
        console.log('-----'); // 目录分隔符
    }
} catch (err) {
    console.error('处理目录时发生错误:', err);
}

}

listFiles(currentDir);


>将 `listsort.js` 放入 视频根目录下
示例:
```bash
node listsort.js

使用ChatGPT翻译英语文件名为中文

翻译为中文:此处为英语字幕列表,换行分隔

使用ChatGPT提取一级目录名

提取所有翻译后的一级目录名,换行分隔,例如:1. 前端软件架构介绍

使用ChatGPT翻译英语文件名为中文

将旧,新名字组合为新的名称对,用$$$组合,换行分隔,输出markdown。例如 1. Course structure.mp4$$$1. 课程结构.mp4

将旧,新名字组合为新的名称对,用```$$$```组合,换行分隔,输出markdown。例如
001 Class Trailer.mp4,001 课程预告片.mp4  
002 IMPORTANT The Course Guide, Overview  Downloadable Resources.mp4,002 重要:课程指南,概述及可下载资源.mp4  
003 Graphic Design Facebook Group - Post projects and join the discussion.mp4,003 平面设计 Facebook 小组 - 发布项目并参与讨论.mp4  

001 What is Graphic Design What Type of Projects Will I Do.mp4,001 什么是平面设计 我将做哪些类型的项目.mp4  
002 The Step-by-Step Process of Becoming a Graphic Designer.mp4,002 成为平面设计师的逐步过程.mp4  

001 The Anatomy of Typography.mp4,001 字体的解剖学.mp4  
002 Different Type Styles.mp4,002 不同的字体风格.mp4  
003 Detailed Review and History of Serif Fonts.mp4,003 字体的详细回顾和历史:衬线字体.mp4  
004 Detailed Review - Sans-Serif Fonts.mp4,004 字体的详细回顾:无衬线字体.mp4  
005 Using Type in Layout and Design.mp4,005 在布局和设计中使用字体.mp4  
006 Font Pairing Basics.mp4,006 字体配对基础.mp4  
007 Design Theory - INTERMISSION.mp4,007 设计理论 - 休息.mp4
WangShuXian6 commented 5 months ago

根据文件夹名称列表,批量创建文件夹

以换行分隔目录名


import os
import tkinter as tk
from tkinter import filedialog, messagebox

class DirectoryCreatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("目录创建器")

        # 创建选择目录按钮
        self.select_button = tk.Button(self.root, text="选择目录", command=self.select_directory)
        self.select_button.pack(pady=10)

        # 创建显示选择目录的标签
        self.selected_directory_label = tk.Label(self.root, text="未选择目录")
        self.selected_directory_label.pack(pady=5)

        # 创建目录名输入框
        self.text_area = tk.Text(self.root, height=10, width=50)
        self.text_area.pack(pady=10)

        # 创建开始创建目录按钮
        self.create_button = tk.Button(self.root, text="开始创建目录", command=self.create_directories)
        self.create_button.pack(pady=10)

        # 存储选择的目录路径
        self.selected_directory = ""

    def select_directory(self):
        self.selected_directory = filedialog.askdirectory()
        if self.selected_directory:
            self.selected_directory_label.config(text=f"选择的目录: {self.selected_directory}")
        else:
            self.selected_directory_label.config(text="未选择目录")

    def create_directories(self):
        if not self.selected_directory:
            messagebox.showerror("错误", "请先选择一个目录")
            return

        directory_names = self.text_area.get("1.0", tk.END).strip().split("\n")
        for dir_name in directory_names:
            if dir_name.strip():
                dir_path = os.path.join(self.selected_directory, dir_name.strip())
                os.makedirs(dir_path, exist_ok=True)

        messagebox.showinfo("完成", "目录创建完成")

if __name__ == "__main__":
    root = tk.Tk()
    app = DirectoryCreatorApp(root)
    root.mainloop()

图片

图片

WangShuXian6 commented 5 months ago

批量将根目录下的vtt字幕转为srt格式字幕【包含子目录下的字幕文件】

这是因为翻译软件默认使用srt字幕 原字幕依然保留

import tkinter as tk
from tkinter import filedialog, messagebox, Label, Button, Listbox, StringVar, Frame, Scrollbar
import os
import re

def convert_vtt_to_srt(vtt_data):
    """Convert VTT format to SRT format."""
    try:
        srt_data = ''
        index = 1
        vtt_data = re.sub(r'WEBVTT.*\n', '', vtt_data)
        vtt_data = re.sub(r'\d{2}:\d{2}:\d{2}\.\d{3} --> \d{2}:\d{2}:\d{2}\.\d{3}',
                          lambda x: x.group(0).replace('.', ','), vtt_data)
        for block in vtt_data.strip().split('\n\n'):
            srt_data += f"{index}\n{block}\n\n"
            index += 1
        return srt_data.strip()
    except Exception as e:
        return None

def update_list(directory):
    """Update the list to show all VTT files in the directory and subdirectories."""
    listbox.delete(0, tk.END)
    files.clear()
    for root, dirs, files_in_dir in os.walk(directory):
        for file in files_in_dir:
            if file.endswith('.vtt'):
                full_path = os.path.join(root, file)
                listbox.insert(tk.END, full_path)
                files[full_path] = None  # None means not yet processed

def process_directory():
    """Process all VTT files in the directory and subdirectories, converting them to SRT format."""
    if not directory_var.get():
        messagebox.showerror("Error", "No directory selected!")
        return
    total_files = len(files)
    processed_files = 0
    for file_path in files:
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                vtt_data = file.read()
            srt_data = convert_vtt_to_srt(vtt_data)
            if srt_data:
                srt_path = file_path.rsplit('.', 1)[0] + '.srt'
                with open(srt_path, 'w', encoding='utf-8') as file:
                    file.write(srt_data)
                files[file_path] = True  # True means success
                listbox.insert(tk.END, f"✔️ Converted: {srt_path}")
            else:
                raise ValueError("Conversion returned None")
        except Exception as e:
            files[file_path] = False  # False means failure
            listbox.insert(tk.END, f"❌ Failed: {file_path}")
        processed_files += 1
        progress_var.set(f"Progress: {int(processed_files * 100 / total_files)}%")
        root.update_idletasks()
    messagebox.showinfo("Conversion Complete", "All files have been processed.")

def choose_directory():
    """Let the user choose a directory and update the list."""
    directory = filedialog.askdirectory()
    if directory:
        directory_var.set(directory)
        update_list(directory)

# Create the main window
root = tk.Tk()
root.title("VTT to SRT Converter")
root.geometry("1100x900")

directory_var = StringVar()
progress_var = StringVar(value="Progress: 0%")
files = {}

# Set up directory selection and display
directory_frame = Frame(root)
directory_label = Label(directory_frame, text="Directory:")
directory_label.pack(side=tk.LEFT)
directory_entry = Label(directory_frame, textvariable=directory_var, width=50)
directory_entry.pack(side=tk.LEFT)
dir_button = Button(directory_frame, text="Browse", command=choose_directory)
dir_button.pack(side=tk.LEFT)
directory_frame.pack(pady=10)

# Set up the file list
listbox = Listbox(root, width=80, height=20)
listbox.pack(pady=10, fill=tk.BOTH, expand=True)

# Set up the scrollbar for the listbox
scrollbar = Scrollbar(root, orient='vertical', command=listbox.yview)
scrollbar.pack(side='right', fill='y')
listbox.config(yscrollcommand=scrollbar.set)

# Set up progress and operation buttons
progress_label = Label(root, textvariable=progress_var)
progress_label.pack(pady=5)
start_button = Button(root, text="Start Conversion", command=process_directory)
start_button.pack(pady=20)

root.mainloop()

image 效果 image

WangShuXian6 commented 5 months ago

批量创建 pyvideotrans 所需要的字幕和文件夹格式【包含子目录】

pyvideotrans要求: 视频同名srt文件必须是原始视频语言字幕。

pyvideotrans 可以使用本地的原字幕和翻译后的字幕,省略音频提取,识别,翻译 阶段。这样可以防止模型的识别幻觉,字幕可以精翻。 但有前提条件:

如果视频是1.mp4,同目录下有1.srt,那么不再识别字幕,直接使用1.srt作为识别后的字幕,仍然会翻译的。 如果你不想翻译,那么在 1.mp4所在文件夹内创建 _video_out/1 文件夹,将 英文字幕改名 en.srt ,中文字幕改名为 zh-cn.srt 放到 _video_out/1 文件夹内。就不再识别和翻译了。 翻译服务必须可用,例如使用免费额google翻译,需要代理。测试不会消耗翻译额度。

情况1:1.mp4,1.srt [中文],1_en.srt[英文]

兼容 1.en.srt[英文] 的情况 参考这个代码,但是要改动,因为现在,子目录下有1.mp4,1.srt,1_en.srt,这种格式的文件。其中1.srt是中文字幕,要复制为1.zh-cn.srt到同目录下。1_en.srt是英语字幕,要复制为1.en.srt到同目录下。这是第一步。然后第二步,将原来的1.srt删除,将1.en.srt复制一份为1.srt,第三步,复制1.zh-cn.srt到_video_out/1 文件夹内改名为 zh-cn.srt,复制1.en.srt到_video_out/1 文件夹内改名为 en.srt。界面同样显示每个文件的处理成功或失败,显示总的进度: 修改前: 图片

修改后: 图片 图片 图片

process_srt_2

import tkinter as tk
from tkinter import filedialog, messagebox, Listbox, StringVar, Frame, Button, Label, Scrollbar
import os
import shutil

def process_videos(directory):
    listbox.insert(tk.END, "Starting processing...")
    root.update_idletasks()
    total_files = 0
    total_success = 0
    total_fail = 0

    for subdir in os.listdir(directory):
        subdir_path = os.path.join(directory, subdir)
        if os.path.isdir(subdir_path):
            for file in os.listdir(subdir_path):
                if file.endswith('.mp4'):
                    base_name = os.path.splitext(file)[0]
                    video_out_path = os.path.join(subdir_path, '_video_out', base_name)
                    if not os.path.exists(video_out_path):
                        os.makedirs(video_out_path)
                        listbox.insert(tk.END, f"Created: {video_out_path}")
                    else:
                        listbox.insert(tk.END, f"Already exists: {video_out_path}")

                    # Step 1: Copy and rename subtitle files
                    zh_srt = os.path.join(subdir_path, f"{base_name}.srt")
                    en_srt_underscore = os.path.join(subdir_path, f"{base_name}_en.srt")
                    en_srt_dot = os.path.join(subdir_path, f"{base_name}.en.srt")

                    en_srt = en_srt_underscore if os.path.exists(en_srt_underscore) else en_srt_dot

                    if os.path.exists(zh_srt):
                        try:
                            shutil.copy(zh_srt, os.path.join(subdir_path, f"{base_name}.zh-cn.srt"))
                            listbox.insert(tk.END, f"Copied: {zh_srt} to {base_name}.zh-cn.srt ✔")
                        except Exception as e:
                            listbox.insert(tk.END, f"Failed to copy {zh_srt}: {e} ✘")
                            total_fail += 1
                    if os.path.exists(en_srt) and not os.path.exists(os.path.join(subdir_path, f"{base_name}.en.srt")):
                        try:
                            shutil.copy(en_srt, os.path.join(subdir_path, f"{base_name}.en.srt"))
                            listbox.insert(tk.END, f"Copied: {en_srt} to {base_name}.en.srt ✔")
                        except Exception as e:
                            listbox.insert(tk.END, f"Failed to copy {en_srt}: {e} ✘")
                            total_fail += 1

                    # Step 2: Replace original .srt with .en.srt from the copied .en.srt
                    try:
                        if os.path.exists(zh_srt):
                            os.remove(zh_srt)
                        if not os.path.exists(os.path.join(subdir_path, f"{base_name}.srt")):
                            shutil.copy(os.path.join(subdir_path, f"{base_name}.en.srt"), zh_srt)
                        listbox.insert(tk.END, f"Replaced original {zh_srt} with {base_name}.en.srt ✔")
                    except Exception as e:
                        listbox.insert(tk.END, f"Failed to replace {zh_srt}: {e} ✘")
                        total_fail += 1

                    # Step 3: Copy to _video_out
                    try:
                        shutil.copy(os.path.join(subdir_path, f"{base_name}.zh-cn.srt"), os.path.join(video_out_path, "zh-cn.srt"))
                        shutil.copy(os.path.join(subdir_path, f"{base_name}.en.srt"), os.path.join(video_out_path, "en.srt"))
                        listbox.insert(tk.END, f"Copied subtitles to {video_out_path} ✔")
                        total_success += 1
                    except Exception as e:
                        listbox.insert(tk.END, f"Failed to copy subtitles to {video_out_path}: {e} ✘")
                        total_fail += 1

                    total_files += 1
                    root.update_idletasks()

    listbox.insert(tk.END, "Processing completed.")
    listbox.insert(tk.END, f"Total files processed: {total_files}")
    listbox.insert(tk.END, f"Total success: {total_success}")
    listbox.insert(tk.END, f"Total fail: {total_fail}")
    messagebox.showinfo("Completed", "All files have been processed and subtitles organized.")

def choose_directory():
    directory = filedialog.askdirectory()
    if directory:
        directory_var.set(directory)
        listbox.delete(0, tk.END)
        for root_dir, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith('.mp4'):
                    listbox.insert(tk.END, file)

def start_conversion():
    if directory_var.get():
        process_videos(directory_var.get())
    else:
        messagebox.showerror("Error", "Please select a valid directory first!")

# Create main window
root = tk.Tk()
root.title("Video and Subtitle Organizer")
root.geometry("1100x900")

directory_var = StringVar()

# Directory frame setup
directory_frame = Frame(root)
directory_label = Label(directory_frame, text="Directory:")
directory_label.pack(side=tk.LEFT, padx=5)
directory_entry = Label(directory_frame, textvariable=directory_var, width=40)
directory_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
dir_button = Button(directory_frame, text="Browse", command=choose_directory)
dir_button.pack(side=tk.LEFT, padx=5)
directory_frame.pack(pady=10, fill=tk.X, expand=True)

# Listbox for displaying operations and statuses
listbox_frame = Frame(root)
listbox_frame.pack(fill=tk.BOTH, expand=True)
listbox = Listbox(listbox_frame, width=150, height=40)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)

# Scrollbar for the listbox
scrollbar = Scrollbar(listbox_frame, orient='vertical', command=listbox.yview)
scrollbar.pack(side='right', fill='y')
listbox.config(yscrollcommand=scrollbar.set)

# Start conversion button
start_button = Button(root, text="Start Organizing", command=start_conversion)
start_button.pack(pady=20)

root.mainloop()

图片

情况2 1.mp4,1.srt [英语],1.en.srt[英文]

import tkinter as tk
from tkinter import filedialog, messagebox, Listbox, StringVar, Frame, Button, Label, Scrollbar
import os
import shutil

def process_videos(directory):
    listbox.insert(tk.END, "Starting processing...")
    root.update_idletasks()
    total_dirs = 0
    total_success = 0

    # 仅在直接子目录中查找和创建 _video_out 目录
    for subdir in os.listdir(directory):
        subdir_path = os.path.join(directory, subdir)
        if os.path.isdir(subdir_path):
            total_dirs += 1
            video_out_path = os.path.join(subdir_path, "_video_out")
            if not os.path.exists(video_out_path):
                os.makedirs(video_out_path)
                listbox.insert(tk.END, f"Created: {video_out_path}")
            else:
                listbox.insert(tk.END, f"Already exists: {video_out_path}")

            root.update_idletasks()

            for file in os.listdir(subdir_path):
                if file.endswith('.mp4'):
                    base_name = os.path.splitext(file)[0]
                    video_dir = os.path.join(video_out_path, base_name)
                    if not os.path.exists(video_dir):
                        os.makedirs(video_dir)
                        total_success += 1
                        listbox.insert(tk.END, f"Created: {video_dir}")
                    else:
                        listbox.insert(tk.END, f"Already exists: {video_dir}")

                    # Copy and rename subtitle files
                    srt_files = [f for f in os.listdir(subdir_path) if f.startswith(base_name) and f.endswith('.srt')]
                    for srt in srt_files:
                        srt_path = os.path.join(subdir_path, srt)
                        if '.en.srt' in srt:
                            shutil.copy(srt_path, os.path.join(video_dir, 'en.srt'))
                        else:
                            shutil.copy(srt_path, os.path.join(video_dir, 'zh-cn.srt'))
                    root.update_idletasks()

    listbox.insert(tk.END, "Processing completed.")
    listbox.insert(tk.END, f"Total directories checked: {total_dirs}")
    listbox.insert(tk.END, f"Total directories created: {total_success}")
    messagebox.showinfo("Completed", "All directories have been processed and subtitles organized.")

def choose_directory():
    directory = filedialog.askdirectory()
    if directory:
        directory_var.set(directory)

def start_conversion():
    if directory_var.get():
        process_videos(directory_var.get())
    else:
        messagebox.showerror("Error", "Please select a valid directory first!")

# Create main window
root = tk.Tk()
root.title("Video and Subtitle Organizer")
root.geometry("1100x900")

directory_var = StringVar()

# Directory frame setup
directory_frame = Frame(root)
directory_label = Label(directory_frame, text="Directory:")
directory_label.pack(side=tk.LEFT, padx=5)
directory_entry = Label(directory_frame, textvariable=directory_var, width=40)
directory_entry.pack(side=tk.LEFT, padx=5)
dir_button = Button(directory_frame, text="Browse", command=choose_directory)
dir_button.pack(side=tk.LEFT, padx=5)
directory_frame.pack(pady=10)

# Listbox for displaying operations and statuses
listbox = Listbox(root, width=150, height=40)
listbox.pack(pady=10)

# Scrollbar for the listbox
scrollbar = Scrollbar(root, orient='vertical', command=listbox.yview)
scrollbar.pack(side='right', fill='y')
listbox.config(yscrollcommand=scrollbar.set)

# Start conversion button
start_button = Button(root, text="Start Organizing", command=start_conversion)
start_button.pack(pady=20)

root.mainloop()

界面: image 实际效果,创建视频同名文件夹,且拷贝中英文字幕到同名文件夹下:

image image image

WangShuXian6 commented 5 months ago

pyvideotrans 可以使用本地的原字幕和翻译后的字幕,省略音频提取,识别,翻译 阶段。这样可以防止模型的识别幻觉,字幕可以精翻。

使用以上代码即可: 1-https://github.com/WangShuXian6/blog/issues/190#issuecomment-2174782912 如果中英文字幕都是srt格式,则此步忽略

2-https://github.com/WangShuXian6/blog/issues/190#issuecomment-2174792095

3-使用js脚本一次获取指定目录下的mp4文件名称【也包含子目录下的mp4】

js代码在 https://github.com/WangShuXian6/blog/issues/190#issuecomment-2158291647 末尾

4-https://github.com/WangShuXian6/blog/issues/190#issuecomment-2158300975

5-https://github.com/WangShuXian6/blog/issues/190#issuecomment-2158291647

WangShuXian6 commented 5 months ago

renameToEnSrt

1.srt 这种实际内容为英文的字幕重命名为 1.en.srt

import tkinter as tk
from tkinter import filedialog, messagebox, Label, Button
import os

def rename_srt_files(directory):
    """遍历目录下的所有子目录,并重命名所有SRT文件为.en.srt格式"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.srt') and not file.endswith('.en.srt'):
                old_path = os.path.join(root, file)
                new_path = os.path.join(root, file.replace('.srt', '.en.srt'))
                os.rename(old_path, new_path)
    messagebox.showinfo("完成", "所有SRT文件已重命名为.en.srt格式。")

def choose_directory():
    """选择目录并重命名文件"""
    directory = filedialog.askdirectory()
    if directory:
        rename_srt_files(directory)

# 创建主窗口
root = tk.Tk()
root.title("SRT to EN.SRT Renamer")
root.geometry("400x150")

# 设置选择目录按钮
choose_button = Button(root, text="选择目录并重命名SRT文件", command=choose_directory)
choose_button.pack(pady=20)

root.mainloop()

image

WangShuXian6 commented 5 months ago

renameToSrt

1.en.srt 这种实际内容为中文的字幕重命名为 1.srt


import tkinter as tk
from tkinter import filedialog, messagebox, Label, Button
import os

def rename_en_srt_files(directory): """遍历目录下的所有子目录,并重命名所有.en.srt文件为.srt格式""" for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.en.srt'): old_path = os.path.join(root, file) new_path = os.path.join(root, file.replace('.en.srt', '.srt')) os.rename(old_path, new_path) messagebox.showinfo("完成", "所有.en.srt文件已重命名为.srt格式。")

def choose_directory(): """选择目录并重命名文件""" directory = filedialog.askdirectory() if directory: rename_en_srt_files(directory)

创建主窗口

root = tk.Tk() root.title("EN.SRT to SRT Renamer") root.geometry("400x150")

设置选择目录按钮

choose_button = Button(root, text="选择目录并重命名EN.SRT文件", command=choose_directory) choose_button.pack(pady=20)

root.mainloop()


![image](https://github.com/WangShuXian6/blog/assets/30850497/e45f8e10-242c-4bcf-a578-30b28e9e55ba)
WangShuXian6 commented 5 months ago

renameVttToEnSrt

将1.vtt这种内容为英文的字幕转换为1.en.srt,且保留源文件


import tkinter as tk
from tkinter import filedialog, messagebox, Button
import os
import shutil

def convert_vtt_to_srt(directory): """遍历目录下的所有子目录,并将所有VTT文件复制并重命名为.en.srt格式""" for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.vtt'): old_path = os.path.join(root, file) new_path = os.path.join(root, file.replace('.vtt', '.en.srt')) shutil.copyfile(old_path, new_path) # 使用shutil.copyfile保留原文件 messagebox.showinfo("完成", "所有VTT文件已被复制并重命名为.en.srt格式。")

def choose_directory(): """选择目录并开始转换过程""" directory = filedialog.askdirectory() if directory: convert_vtt_to_srt(directory)

创建主窗口

root = tk.Tk() root.title("VTT to EN.SRT Converter") root.geometry("400x150")

设置选择目录按钮

choose_button = Button(root, text="选择目录并转换VTT文件", command=choose_directory) choose_button.pack(pady=20)

root.mainloop()


![image](https://github.com/WangShuXian6/blog/assets/30850497/cf6f6a0d-aa39-4516-9856-23d5e09c6049)