1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#!/usr/bin/env python
# encoding: utf-8
import re
import os
import sys
from decimal import Decimal as D
def filter_filetype(path,filetype):
filetype = filetype.lower()
filenames = [filename for filename in os.listdir(path)
if os.path.isfile(os.path.join(path, filename))] #Get all regular files
filter_filename_list = [filename for filename in filenames if filename.endswith(filetype)]
return filter_filename_list
def min_sec_str2sec_str(min_sec_str):
'''minute:second change to second'''
(m,s) = min_sec_str.split(":")
sec = 60*D(m)+D(s)
sec_str = str(sec)
return sec_str
def format_file_time(filename):
with open(filename,"r") as input_file:
content = input_file.read()
thetime = re.compile(r"\[(\d{2}:.{5})\]")
#match is list: ['00:00.12',...]
match = thetime.findall(content)
sec_strs = [min_sec_str2sec_str(min_sec_str) for min_sec_str in match ]
#再一次推导,使其成为新的格式,注意边界
new_format = ["{:<6s} {:>6s} ".format(sec_str,sec_strs[i+1]) for i,sec_str in enumerate(sec_strs) if i<len(sec_strs)-1] #最后一行是边界
#单独添加最后一行
#new_format.append(sec_strs[-1])#list本身被改变了
#print new_format
#exit()
filename_split = filename.split(".")
#后缀改为txt
out_filename = filename_split[0]+"_output.txt"
output_file = open(out_filename,"w")
with open(filename,"r") as input_file:
i = 0 #行号标记
for line in input_file:
if i==len(sec_strs)-1:
#最后一行不要
break
result_line = thetime.sub(new_format[i],line)
#print result_line
output_file.write(result_line)
i = i+1
output_file.close()
if __name__ == "__main__":
path = sys.argv[1]
filetype = sys.argv[2]
filter_filename_list = filter_filetype(path,filetype)
for filename in filter_filename_list:
print(os.path.join(path,filename))
format_file_time(os.path.join(path,filename))
#注意路径
|