編寫一個程序通過一個文本文件的讀取和計算出的一天的小時的分佈對於每個消息。您可以通過查找時間,然後使用冒號第二次拆分字符串,從「發件人」行拉出小時。行的文本文件的
例子:
「從[email protected]週六1月5日9時14分十六秒2015」
一旦你已經積累了各計數小時,打印出計數,按小時排序,如下所示。
[預期結果]
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
這意味着,我需要拉出「九時14分16秒」部分,然後拉出小時「09」一次。
我會用 '#' 評論什麼,我已經做了以下
[我的代碼]
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt" #if nothing is entered by user, it goes straight to the desired file
handle = open(name, 'r') # open and read the file
count = dict() # initialise count to a empty dictionary
for text in handle: #for loop to loop through lines in the file
text = text.rstrip() #r.strip() to to remove any newline "\n"
if not text.startswith('From '): continue # find lines that starts with "From "
text = text.split() #split the line into list of words
line = text[5] #time is located at the [5] index
time = line.split(':') #split once more to get the hour
hour = time[0] #hour is on the [0] index
count[hour] = count.get(hour, 0) + 1
print count
[我的結果]
{'09': 1} ← Mismatch
{'09': 1, '18': 1}
{'09': 1, '18': 1, '16': 1}
{'09': 1, '18': 1, '16': 1, '15': 1}
{'09': 1, '18': 1, '16': 1, '15': 2}
{'09': 1, '18': 1, '16': 1, '15': 2, '14': 1}
{'09': 1, '18': 1, '16': 1, '15': 2, '14': 1, '11': 1}
{'09': 1, '18': 1, '16': 1, '15': 2, '14': 1, '11': 2}
{'09': 1, '18': 1, '16': 1, '15': 2, '14': 1, '11': 3}
(deleted portion of the result)
{'09': 2, '18': 1, '16': 1, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1}
{'09': 2, '18': 1, '16': 1, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1, '17': 1}
{'09': 2, '18': 1, '16': 1, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1, '17': 2}
{'09': 2, '18': 1, '16': 2, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1, '17': 2}
{'09': 2, '18': 1, '16': 3, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1, '17': 2}
{'09': 2, '18': 1, '16': 4, '15': 2, '14': 1, '11': 6, '10': 3, '07': 1, '06': 1, '04': 3, '19': 1, '17': 2}
有人可以幫助我放哪兒我錯了?我正朝着正確的方向前進嗎? 感謝任何意見和建議,即時編程新手請溫柔和抱歉的任何格式錯誤。
我不明白你輸出的問題是什麼,你能更明確嗎?順便說一下,請查看[Counter](https://pymotw.com/3/collections/counter.html)模塊,看起來它可能非常合適。 – iodbh