繁体   English   中英

在文本文件中的每4行读取,编辑和写入

[英]Reading, editing, and writing over every 4th line in a text file

长时间读者第一次问问。

我正在编写一些我需要编辑时间戳的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()

计算效果很好,但问题是它将所有新行转储到文件的开头,而不是写入每个时间戳行并跳过其余的。

我很想听听你们的想法! 我已经和它搏斗了一段时间并尝试了很多东西但是还没能完成它。

谢谢!

您可以尝试枚举 ,而迭代的lines ,然后做同样的过程:

# Reading code here ...

for index, line in enumerate(lines):
    if index % 4 == 0:
        # Your code here ...

希望它有帮助:)

固定它!

我所要做的就是添加:

else:
        video.write(l)

到if语句。 这样,如果它匹配我的参数,则运行计算并写入新行,但如果不匹配,则只写入旧行。

谢谢大家!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM