gpt4 book ai didi

python - 如何在给定文件的给定行号处附加时间?

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:24 25 4
gpt4 key购买 nike

我想通过检查文本文件中的行数在文本前面的每一行中写入时间,因为我想按照此链接将此文本文件转换为 .srt 文件。 https://unix.stackexchange.com/questions/111024/how-to-convert-a-txt-subtitle-file-to-srt-format

每一行都是 1 秒。(从 00:00:00 开始第一行:) 我的文件有很多行(500-1000 行)来自

.......Text......... (first line)
.......Text......... (second line)
.......Text......... (third line)
.
.
.
.......Text......... (60 line)
.......Text......... (61 line)
.
.
.................... (3600 line)

到此

00:00:01:.......Text......... (first line)
00:00:02:.......Text......... (second line)
00:00:03:.......Text......... (third line)
.
.
.
00:01:00:.......Text......... (60 line)
00:01:01:.......Text......... (61 line)
.
.
01:00:00:.................... (3600 line)

我想检查行号并在每行前面写入文本,但我的代码中有一个逻辑错误来检查行号并打开文件在该行写入文本。我不知道如何编写 for 循环并比较行数。我对这个很菜鸟。

def numberline(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
numberline("/home/pi/gtest.txt"))

dataFile = open("/home/pi/gtest.txt", "w")
for line in range(numberline("/home/pi/gtest.txt")):
dataFile.write("00:00:%02d:\n" % line)
dataFile.close()

最佳答案

试试这个(假设 a.txt 是一个包含多行的文本文件)

import datetime


def make_time(num_of_seconds):
hours = 0 if num_of_seconds < 3600 else num_of_seconds / 3600
minutes = 0 if num_of_seconds < 60 else (num_of_seconds - hours * 3600) / 60
seconds = num_of_seconds - (minutes * 60) - (hours * 3600)
t = datetime.time(hours,minutes,seconds)
return t.strftime("%H:%M:%S")


new_lines = []
with open('a.txt', 'r') as f_in:
lines = f_in.readlines()
for idx, line in enumerate(lines):
new_lines.append('{}:{}'.format(make_time(idx), line))
for l in new_lines:
print(l.strip())

关于python - 如何在给定文件的给定行号处附加时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169603/

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