如何删除.srt文件中句子后的数字

如何解决如何删除.srt文件中句子后的数字

我有很多字幕文件,像这样的每个句子后面都有一个数字,

23
00:01:32,670 --> 00:01:40,110
It's basically double the amount of work that he used to have. But that's not all because he gets complaints
23

24
00:01:40,110 --> 00:01:46,250
from users saying that "Hey in your app some of the layouts look really weird".
24

25
00:01:46,260 --> 00:01:47,670
"It doesn't look right."
25

所以我想删除它怎么办?

注意::我有一点编程经验

解决方法

将“RemoveDoubleNumbering.exe”放在字幕所在的文件夹中并打开它。将处理此文件夹及其所有子文件夹中的字幕。还将创建备份。

需要 .Net Framework 4.5+。

如果有人担心病毒,请自行编译:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RemoveDoubleNumbering
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0 && args[0] == "restore")
            {
                Console.WriteLine("Starting to restore backups");
                RestoreSubtitlesFromBackup(GetCurrentDirectory());
                Console.WriteLine("Backups restored.");
                return;
            }

            var subtitlesDirectory = GetSubtitlesDirectory(args);
            var subtitleFiles = GetSubtitleFiles(subtitlesDirectory);
            RemoveDoubleNumbering(subtitleFiles);
        }

        /// <summary>Gets subtitles directory.</summary>
        /// <param name="args">Program arguments.</param>
        /// <returns>Current directory or directory from arguments.</returns>
        static string GetSubtitlesDirectory(string[] args)
        {
            if (args.Length == 0)
            {
                return GetCurrentDirectory();
            }

            return args[0];
        }

        /// <summary>Gets current directory of exe.</summary>
        /// <returns>Current directory.</returns>
        static string GetCurrentDirectory()
        {
            try
            {
                return Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return null;
            }
        }

        /// <summary>Removes double numbering from subtitle files. Overwrites existing files.</summary>
        /// <param name="subtitleFiles">Subtitle files path.</param>
        static void RemoveDoubleNumbering(IEnumerable<string> subtitleFiles)
        {
            foreach (var subtitleFile in subtitleFiles)
            {
                RemoveDoubleNumbering(subtitleFile);
            }
        }

        /// <summary>Removes double numbering from subtitle file. Overwrites existing file.</summary>
        /// <param name="subtitleFile">Subtitle file path.</param>
        static void RemoveDoubleNumbering(string subtitleFile)
        {
            if (!CreateSubtitleBackup(subtitleFile))
            {
                Console.WriteLine($@"Failed to create backup for ""{subtitleFile}""");
                Console.WriteLine($@"The ""{subtitleFile}"" will be skipped");
                return;
            }

            try
            {
                Console.WriteLine($@"Removing double numbering in ""{subtitleFile}""");
                var subtitleText = File.ReadAllText(subtitleFile);
                var subtitleLines = subtitleText.Split(new string[] { Environment.NewLine },StringSplitOptions.None);
                var startIndex = GetStartIndex(subtitleLines);
                var newSubtitleLines = new List<string>();
                for (int currentLineIndex = startIndex; currentLineIndex < subtitleLines.Length; currentLineIndex++)
                {
                    if (!IsDoubleNumbering(subtitleLines,startIndex,currentLineIndex))
                    {
                        newSubtitleLines.Add(subtitleLines[currentLineIndex]);
                    }
                }
                var newSubtitleText = string.Join(Environment.NewLine,newSubtitleLines);
                newSubtitleText = newSubtitleText.Trim() + Environment.NewLine + Environment.NewLine;
                File.WriteAllText(subtitleFile,newSubtitleText);
                Console.WriteLine($@"Deletion of double numbering in ""{subtitleFile}"" completed.");
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }

        /// <summary>Checks if the current line is the double numbering.</summary>
        /// <param name="subtitleLines">Subtitle lines.</param>
        /// <param name="startIndex">Start index.</param>
        /// <param name="currentLineIndex">Current line index.</param>
        /// <returns><see langword="true"/> if the current line is the double numbering; otherwise <see langword="false"/>.</returns>
        static bool IsDoubleNumbering(IEnumerable<string> subtitleLines,int startIndex,int currentLineIndex)
        {
            var arrowLineIndex = currentLineIndex - 2;
            try
            {
                var isDoubleNumbering = arrowLineIndex >= startIndex
                 && subtitleLines.ElementAt(currentLineIndex).IsNumber()
                 && subtitleLines.ElementAt(arrowLineIndex).Contains("-->");
                return isDoubleNumbering;
            }
            catch (Exception exc)
            {
                Console.Write(exc.Message);
                return false;
            }

        }

        /// <summary>Gets start index.</summary>
        /// <param name="subtitleLines">Subtitle lines.</param>
        /// <returns>1 if garbage exists in the first line; otherwise 0.</returns>
        static int GetStartIndex(IEnumerable<string> subtitleLines)
        {
            if (subtitleLines.Count() > 0 && subtitleLines.First() != "1")
            {
                return 1;
            }

            return 0;
        }

        /// <summary>Gets .srt subtitle files. Gets files from directory and all its subdirectories.</summary>
        /// <param name="directory">Directory where subtitle files are located.</param>
        /// <param name="mask">Files mask.</param>
        /// <returns>Full paths to subtitle files.</returns>
        static IEnumerable<string> GetSubtitleFiles(string directory,string mask = "*.srt")
        {
            try
            {
                return Directory.EnumerateFiles(directory,mask,SearchOption.AllDirectories);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return new string[] { };
            }
        }

        /// <summary>Creates subtitle file backup.</summary>
        /// <param name="subtitleFile">subtitle file path.</param>
        /// <returns><see langword="true"/> if the backup is successfully created; otherwise <see langword="false"/>.</returns>
        static bool CreateSubtitleBackup(string subtitleFile)
        {
            try
            {
                var backupName = Path.GetFileName(subtitleFile) + ".backup";
                var backupPath = Path.Combine(Path.GetDirectoryName(subtitleFile),backupName);
                if (!File.Exists(backupPath))
                {
                    File.Copy(subtitleFile,backupPath);
                }
                return true;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return false;
            }
        }

        /// <summary>Restore subtitles from backups.</summary>
        /// <param name="directory">Directory with subtitles.</param>
        /// <returns><see langword="true"/> if the subtitles is successfully resotred; otherwise <see langword="false"/>.</returns>
        static bool RestoreSubtitlesFromBackup(string directory)
        {
            try
            {
                var backupFiles = GetSubtitleFiles(directory,"*.srt.backup");
                foreach (var backupFile in backupFiles)
                {
                    var originalFileName = Path.GetFileNameWithoutExtension(backupFile);
                    var originalFile = Path.Combine(Path.GetDirectoryName(backupFile),originalFileName);
                    if (File.Exists(originalFile))
                    {
                        File.Delete(originalFile);
                    }
                    File.Move(backupFile,originalFile);
                }
                return true;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                return false;
            }
        }
    }

    /// <summary>Extends the string class.</summary>
    static class StringExtension
    {
        /// <summary>Checks if a string is actually a number.</summary>
        /// <param name="line">The string itself.</param>
        /// <returns><see langword="true"/> if the string is a number; otherwise <see langword="false"/>.</returns>
        public static bool IsNumber(this string line)
        {
            int number;
            if (int.TryParse(line,out number))
            {
                return true;
            }
            return false;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-