gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:50:25 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com