python - 为文本文件中的所有时间戳添加 5 秒

标签 python regex file python-datetime

我有一个文本文件,其中包含如下所示的信息:

341
00:33:17,72 --> 00:33:24,05
this happen because si se puede
yes we can. Thank you very much.

我正在尝试查找所有时间实例并将时间添加五秒。这是我到目前为止所拥有的:

import re
import string
from datetime import datetime, timedelta
import fileinput



fr = open('project.txt')
text = fr.read()
fr.close()
regex = r"(\d+):(\d+):(\d+),(\d+)"
matches = re.finditer(regex, text, re.MULTILINE)

def changeTimes():
    for matchNum, match in enumerate(matches, start=1):

        print("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum=matchNum, start=match.start(),
                                                                            end=match.end(), match=match.group()))
        t1 = datetime.strptime(match.group(), "%H:%M:%S,%f")  # put your time instead
        delta = timedelta(seconds=5)  # seconds, minutes, hours, whatever
        t1 += delta
        print(t1.strftime("%H:%M:%S,%f")[:-4])
        with fileinput.FileInput('project.txt', inplace=True, backup='.bak') as file:
            for line in file:
                print(line.replace(r"(\d+):(\d+):(\d+),(\d+)", t1.strftime("%H:%M:%S,%f")[:-4]), end='')

我在大量评论下面调用 changeTimes()

我没有收到任何错误,也没有对文本文件进行任何更改。这是为什么?

最佳答案

假设您的时间采用固定格式,请使用 (\b(?:\d\d:){2}\d\d,\d\d\b) 并保留您的 fileinput.FileInputinplace=True (无需在单独的文件读取上进行模式匹配 - 您可以在一个循环中完成所有操作)。为 re.sub 提供 lambda 函数,该函数可以解析、递增并重新格式化每行的匹配时间字符串。

import fileinput
import re
from datetime import datetime, timedelta

def add_seconds(x, fmt="%H:%M:%S,%f", seconds=5):
    return (datetime.strptime(x, fmt) +
            timedelta(seconds=seconds)).strftime(fmt)

pattern = r"(\b(?:\d\d:){2}\d\d,\d\d\b)"
replacement = lambda x: add_seconds(x.group(0))[:11]

with fileinput.FileInput("project.txt", inplace=True, backup=".bak") as f:
    for line in f:
        print(re.sub(pattern, replacement, line), end="")

输出:

341
00:33:22,72 --> 00:33:29,05
this happen because si se puede
yes we can. Thank you very much.

关于python - 为文本文件中的所有时间戳添加 5 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038147/

相关文章:

python - 动态实例化对象

python - 如何在没有服务器的情况下将 mlflow 指标和参数保存到 s3 存储桶?

javascript - 根据日期(时间)在 JavaScript 中复制文件

c - 有没有更好的方法来管理C中的文件指针?

python - 从系列创建数据帧时保持列顺序

java - A[j] = 2∗A[i] in list with better than O(n^2) runtime

Java扫描仪问题

php - 替换,但仅在某些情况下包含分隔符

java - Java 中的正则表达式 : find all instances of [char1] but only if they are not preceded by [char2]

java - 如何使用java在给定路径的 super 目录中查找特定文件夹