我试图用两种不同的时间格式读取文件,然后计算每小时出现第二次时间格式的次数。这是我的第一个Python脚本,在我认为我正在取得重大进展之后,有点失落。我在输出文件中获得了独特的时间,但没有计数,我无法弄清楚我要出错的地方。尝试计算每个独特小时的发生次数
我非常感谢您提供的任何帮助。谢谢!
这是一个例子我文件 -
KABH, 11:17:00, 04:30:00
KABH, 11:18:00, 04:31:00
KABH, 11:19:00, 04:33:00
KABH, 11:20:00, 05:34:00
KABH, 11:32:00, 05:46:00
KABH, 11:33:00, 02:47:00
KABH, 11:34:00, 02:48:00
KABH, 11:35:00, 02:49:00
这是我目前正在运行的获得电流输出的结果
Python libs
import sys, glob, os, subprocess, calendar, string
# Input file
infile = "test.txt"
# Open file
fin = open(infile,"r")
data = fin.readlines()
# Lists to hold counts
stn = []
cnts = []
UTC = []
NST = []
HRS = []
# Loop over each line and count the number of times each hour is found
for lines in data:
d = string.split(lines,", ")
if not d[0] in stn:
stn.append(d[0])
UTC.append(d[1])
NST.append(d[2])
t = d[2].split(":")
if not t[0] in HRS:
HRS.append(t[0])
# Loop over all the unique times and count how the number of occurrences
for h in HRS:
cnt = 0
for l in data:
t2 = string.split(l,":")
if t2[0] == h:
cnt = cnt + 1
cnts.append(cnt)
# Open a file and write the info
fout = open("data.csv","w")
cnt = 0
while cnt < len(HRS):
fout.write('%02d,%02d\n' % (int(HRS[cnt]),int(cnts[cnt])))
cnt = cnt + 1
fout.close()
示例代码文件 -
04,00
05,00
02,00
作为你的代码是缩进现在它是错误的。你能解决它吗?否则,我们会失去评论什么是严重缩进的时间。 – trincot
是不是因为当你比较't2 [0]'到'h'时,'t2 [0]'是* first *时间列的小时而不是第二个?在你的第一个循环中,'t2 [0]'是''KABH,11'',而不是'4',对吧?在你声明't2'之后,打印它,你会明白我的意思。你用冒号分隔整行,所以't2 [0]'是第一个冒号左边的所有内容。所以't2 [0] == h'总是返回false,'cnt'永远不会增加。 – Anonymous
@jphollowed你是完全正确的!我不能相信我让我得到了。无论出于何种原因,我认为我只是分裂第三列,但我显然分裂了字符串。谢谢你指出。我知道这会变得愚蠢和简单。谢谢! – AtmoSci