【问题标题】:Why do I need to use [6] to slice out the time in the following code?为什么我需要在下面的代码中使用 [6] 来分割时间?
【发布时间】:2018-12-26 11:13:11
【问题描述】:

编写一个程序来通读 mbox-short.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吗?

我需要从中提取小时的行如下所示: 来自 stephen.marquard@uct.ac.za 1 月 5 日星期六 09:14:16 200

【问题讨论】:

  • 我们怎么可能在没有看到任何数据的情况下判断?
  • 您能否从有效的 .csv 文件中添加至少一行?
  • 如果你认为基于 1,你永远不会成为世界排名第一的程序员。
  • 我最好的猜测是你不知道索引从 0 开始。你也没有分片,你正在索引列表。
  • 对不起,我匆忙忘记了数据,我已经编辑了问题。

标签: python python-3.x


【解决方案1】:

是的,你说得对,这个例子中的索引应该是 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

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 2013-06-20
    • 1970-01-01
    • 2020-12-22
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多