【发布时间】:2018-10-25 10:07:41
【问题描述】:
长期读者第一次提问。
我正在处理一些需要为其编辑时间戳的 vtt(隐藏式字幕)文件。文件格式如下:
177
00:07:37.450 --> 00:07:39.690
- [Liz] How would you suggest an organization devise
178
00:07:39.690 --> 00:07:41.719
the accountabilities for culture?
179
00:07:41.719 --> 00:07:43.690
- [Tamara] It is a shared accountability
我编写了以下代码来读取文件,计算新的时间戳(慢 5%)并吐出新的时间戳:
from sys import argv
script, filename = argv
adjustment = input("Adjustment multiplier: ")
video = open(filename, "r+")
lines = video.readlines()
video.seek(0)
for l in lines:
if l[:2] == "00":
#here I've omitted a lot of calculations to turn the timestamps
#into milliseconds, apply the adjustment multiplier, and turn them back into
#minutes, seconds, and milliseconds.
new_line = str(#concatenation of new values into timestamp format)
video.write(new_line)
video.close()
计算效果很好,但问题是它会将所有新行转储到文件的开头,而不是覆盖每个时间戳行并跳过其余行。
我很想听听你们的想法!我已经为此苦苦挣扎了一段时间,并尝试了很多东西,但都无法让它发挥作用。
谢谢!
【问题讨论】:
-
不要覆盖同一个文件,而是写入一个单独的文件,然后在必要时重命名它。写入同一文件有中途失败的风险,然后文件已部分更新。
-
此外,文本文件的行接口不允许将文件指针定位在行首:文件在一个大缓冲区中以块的形式读取,并从该缓冲区中提取行,但文件指针在当前 chunk 之后,可能远远超出当前行。
-
将文件内容读入内存,关闭文件,对内存中的数据进行所有修改,用修改后的数据创建一个新文件(如果需要,与旧文件同名)覆盖它)。
-
srtfix 我刚才提到的完全符合您的要求(我自己写了这样一个工具,该死的 23.976 帧速率......)
标签: python