【发布时间】:2015-05-20 19:14:08
【问题描述】:
我正在尝试使用 OrderedDict() 来跟踪单词的实例。我有按天组织的数据,我想计算当天“foo”实例的数量。每条线都按天索引。使用 defaultdict 给了我我想要的东西,但是,当然,没有排序:
from collections import defaultdict
counter = defaultdict(int)
w = open('file.txt', 'r')
y = w.readlines()
for line in y:
day,words = line[:6], line[14:]
if re.search(r"foo", words):
counter[day] += 1
如果我使用 OrderedDict,我该如何做同样的事情,以便按照读取的方式对数据进行排序?如果我使用
for key, value in sorted(counter.items()):
print(key, value)
然后我按字母顺序获取列表。我知道我可以将日期读入一个数组,然后基于此迭代键,但是,这似乎非常低效。
假设我的文本文件如下所示:
Sep 1, 2014, 22:23 - ######: Here is a foo
Sep 1, 2014, 22:23 - ######: Not here
Sep 2, 2014, 19:09 - ######: foo sure
Sep 2, 2014, 19:57 - ######: footastic
Sep 2, 2014, 19:57 - ######: foo-king awesome
Sep 2, 2014, 19:57 - ######: No esta aqui
我想打印我的字典:
('Sep 1,', 1)
('Sep 2,', 3)
【问题讨论】:
标签: python counter ordereddictionary