Skip to main content
 首页 » 编程设计

Python 2 无法获取键和值(字典和元组)

2025年05月04日18kenshinobiy

[任务]

编写一个程序来读取文本文件并计算出每条消息在一天中的小时分布。您可以通过查找时间然后使用冒号再次拆分字符串,从“From”行中提取小时。

文本文件的一行示例:

“来自 lauren.marquard@oul.ab.bc 2015 年 1 月 5 日星期六 09:14:16”

一旦您累积了每小时的计数,打印出计数,按小时排序,如下所示。

[预期结果]

04 3 
06 1 
07 1 
09 2 
10 3 
11 6 
14 1 
15 2 
16 4 
17 2 
18 1 
19 1 

这意味着我需要拉出“09: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} 

谁能帮我看看哪里出错了?我正朝着正确的方向前进吗? 感谢任何反馈和建议,我是编程新手,对于任何格式错误,请保持温和和抱歉。

请您参考如下方法:

删除 print count 并在循环的末尾和外部添加以下行:

for key in sorted(count.keys()): 
    print key, count[key]