我想通过检查文本文件中的行数在Text前面的每一行中写入时间,因为我想将此文本文件转换为此链接后的.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)
我想检查行号并在每行前面写上文字, 但是我的代码中存在逻辑错误,无法检查行号并在该行打开文件写入文本。 我不知道如何编写循环并比较行数。我不是这个菜。
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()
答案 0 :(得分:0)
尝试一下(假设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())