试图计算每个独特小时的出现次数

时间:2016-12-01 22:44:21

标签: python counting

我尝试使用两种不同的时间格式读取文件,然后计算第二次格式的每小时出现的次数。这是我的第一个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

1 个答案:

答案 0 :(得分:1)

您可以使用dictionaryhour保存为密钥,在第一次遇到密钥时创建一个空列表,并将1附加到列表中。最后,检查每个键的列表长度

counter_dict = dict()
with open("sample.csv") as inputs:
    for line in inputs:
        column1, time1, time2 = line.split(",")
        counter_dict.setdefault(time2.split(":")[0].strip(), list()).append(1)

for key, value in counter_dict.iteritems():
    print "{0},{1}".format(key, len(value))

输出结果为:

02,3
04,3
05,2