'''
文本内容为:
001 08:00:20 0
001 08:15:15 1
001 08:25:16 2
004 10:23:17 0
002 16:45:59 0
'''
#计算每一小时内这个0的个数
#代码如下:
file = open(r'the path of txt','r')
for time in ['08','09','10','11','12','13','14','15','16']:
count = 0
for line in file:
if line[4:6] == time and line[-2] == '0':count +=1
print('%s:00:00 - %s:59:59 : %d'%(time,time,count))
#说明:the path of txt 是一个文本文件的路径
'''
08:00:00 - 08:59:59 : 1
09:00:00 - 09:59:59 : 0
10:00:00 - 10:59:59 : 0
11:00:00 - 11:59:59 : 0
12:00:00 - 12:59:59 : 0
13:00:00 - 13:59:59 : 0
14:00:00 - 14:59:59 : 0
15:00:00 - 15:59:59 : 0
16:00:00 - 16:59:59 : 0
'''
'''
08:00:00 - 08:59:59 : 1
09:00:00 - 09:59:59 : 0
10:00:00 - 10:59:59 : 1
11:00:00 - 11:59:59 : 0
12:00:00 - 12:59:59 : 0
13:00:00 - 13:59:59 : 0
14:00:00 - 14:59:59 : 0
15:00:00 - 15:59:59 : 0
16:00:00 - 16:59:59 : 1
'''
1、打开文件要放在for循环内,这样才能完整的遍历;
2、txt文件读取后,会有换行符干扰,要先去除。
for time in ['08','09','10','11','12','13','14','15','16']:
file = open(r't.txt','r')
count = 0
for line in file:
line = line.strip().split(' ') # 这里要先去掉换行符,否则有干扰
if line[1].split(':')[0] == time and line[-1] == '0':
count +=1
print('%s:00:00 - %s:59:59 : %d'%(time,time,count))
file = open('test.txt','r')
x = file.readlines()
for time in ['08','09','10','11','12','13','14','15','16']:
count = 0
for line in x:
if line[4:6] == time and line[-2] == '0':count +=1
print('%s:00:00 - %s:59:59 : %d'%(time,time,count))