为什么我需要在下面的代码中使用[6]来划分时间?

2024-05-14 20:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个程序来读取mbox-短.txt并计算出每封邮件在一天中按小时的分布情况。你知道吗

您可以从“from”行中提取小时,方法是找到时间,然后使用冒号再次拆分字符串。你知道吗

一旦你积累了每小时的计数,打印出来的计数,按小时排序如下所示。你知道吗

name = input('Enter file name: ')
if len(name)<1:
    name = 'mbox-short.txt'
hand = open(name)
counts = dict()


for line in hand:
    if not line.startswith('From '):
        continue
    words = line.split(' ')
    words = words[6]
    #print(words.split(':'))
    hour = words.split(':')[0]
    counts[hour] = counts.get(hour, 0) + 1
for k,v in sorted(counts.items()):
     print(k,v)

我不得不用[6]在电子邮件中划出时间。但不是应该是5吗?你知道吗

我需要从中提取时间的行如下所示: 从斯蒂芬·马夸德@uct.ac.za公司1月5日星期六09:14:16 200


Tags: nameintxtforifline时间计数
1条回答
网友
1楼 · 发布于 2024-05-14 20:25:17

是的,你说得对,索引应该是5。顺便说一下,collections模块中有一个内置对象。您可以这样重写代码:

from collections import Counter

counter = Counter()

name = input('Enter file name: ')
if len(name) < 1:
    name = 'mbox-short.txt'

with open(name) as fp:
    for line in fp:
        if line.startswith('From'):
            words = line.split(' ')
            time = words[5]
            hour = time.split(':')[0]
            counter[hour] += 1
for hour, freq in sorted(counter.items(), key=lambda x: int(x[0])):
     print(hour, freq)

您还可以通过以下方式访问最常用的项目:

counter.most_common(10) # it'll show you the first 10 most common items

相关问题 更多 >

    热门问题