2016-11-01 31 views
0

我写了一个程序来回答这个问题。它说我的程序没有输出。为什么我的程序没有输出?

问题: 编写一个程序来读取mbox-short.txt文件,并找出每个消息在一天当中的小时分布情况。您可以通过查找时间,然后使用冒号第二次拆分字符串,从“发件人”行拉出小时。

From [email protected] Sat Jan 5 09:14:16 2008 

一旦累计了每小时的计数值,就按照下图所示打印计数,按小时排序。

所需的输出:

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

我的代码:

name = raw_input("Enter file:") 
if len(name) < 1 : name = "mbox-short.txt" 
handle = open(name) 

counts = dict() 

for line in handle: 
    if not line.startswith('From'): 
     continue 

     words = line.split() 

     time = words[5] 

     timesplit = time.split(':') 

     hour = timesplit[0] 

     for x in hour: 
      counts[x] = counts.get(x, 0) + 1 

lists = list() 

for key, val in counts.items(): 
    lists.append((key, val)) 
    lists.sort(reverse=True) 

for val, key in lists: 
    print key, val 
+1

您确定您的代码已正确粘贴到此页面中吗?那么'words = line.splite()'后面的代码将永远不会执行,因为它与'continue'具有相同的缩进。 – ymonad

+0

我首先必须检查一行是否以'From'开头。如果continue没有让代码一次又一次地运行,直到它找到一个以'From'开头的行。然后它执行下面的代码。 –

回答

0

我猜你通过将以下代码到如果indentedStatementBlock犯这样的错误。

words = line.split() 

    time = words[5] 

    timesplit = time.split(':') 

    hour = timesplit[0] 

    for x in hour: 
     counts[x] = counts.get(x, 0) + 1 
0

您有一个缩进问题。没有任何东西超过继续在你的循环中将被处理。我建议您将if语句更改为if line.startswith('From'):,然后彻底删除继续。

你为什么要这样for x in hour:?小时似乎是一个两个字符的字符串,所以当你迭代'08'时,x将等于'0',然后'8'。只需数小时。

另外,counts.items()创建一个元组列表,所以你不需要遍历该列表来创建一个新的元组列表。

lists = counts.items() 
lists.sort(reverse=True) 

此外,你应该养成再次关闭文件的习惯。

编辑: 为了完整起见,我这是怎么会接近同一个问题:

from collections import Counter 

def extract_hour(line): 

    return line.split()[5].split(':')[0] 

lists = Counter(extract_hour(line) for line in open("mbox-short.txt") if line.startswith('From')).items() 
0

经过反复试验,并从这里以前的答案的建议一点帮助,我已经想出了解决方案和我的代码工作!

name = raw_input("Enter file:") 
if len(name) < 1 : name = "mbox-short.txt" 
handle = open(name) 

counts = dict() 

for line in handle: 
    line = line.rstrip() 
    if line == '': continue 
    if line.startswith('From '): 
     words = line.split() 
     time = words[5] 
     tsplit = time.split(":") 
     counts[tsplit[0]] = counts.get(tsplit[0], 0) + 1 


lists = list() 

for key, val in counts.items(): 
    lists.append((key, val)) 

lists.sort() 

for val, key in lists: 
    print val, key 
相关问题