2016-12-01 73 views
1

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

作为你的代码是缩进现在它是错误的。你能解决它吗?否则,我们会失去评论什么是严重缩进的时间。 – trincot

+1

是不是因为当你比较't2 [0]'到'h'时,'t2 [0]'是* first *时间列的小时而不是第二个?在你的第一个循环中,'t2 [0]'是''KABH,11'',而不是'4',对吧?在你声明't2'之后,打印它,你会明白我的意思。你用冒号分隔整行,所以't2 [0]'是第一个冒号左边的所有内容。所以't2 [0] == h'总是返回false,'cnt'永远不会增加。 – Anonymous

+1

@jphollowed你是完全正确的!我不能相信我让我得到了。无论出于何种原因,我认为我只是分裂第三列,但我显然分裂了字符串。谢谢你指出。我知道这会变得愚蠢和简单。谢谢! – AtmoSci

回答

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 
+0

哇。这比我做这件事要容易得多。非常感谢你做的这些。 – AtmoSci

+0

很高兴帮助:) – haifzhan

相关问题