我試圖用兩種不同的時間格式讀取文件,然後計算每小時出現第二次時間格式的次數。這是我的第一個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