使用OrderedDict计算实例

时间:2015-05-20 19:14:09

标签: python counter ordereddictionary

我正在尝试使用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)

2 个答案:

答案 0 :(得分:1)

您可以检查day是否在OrderedDict中。如果是,请添加,如果未将其设置为1

counter = OrderedDict()

w = open('file.txt', 'r')
y = w.readlines()
for line in y:
    day,words = line[:6], line[14:]
    if re.search(r"foo", words):
        if day in counter:
            counter[day] += 1
        else:
            counter[day] = 1

当然,OrderedDict将在源文本文件中每天第一次出现时排序。

相反,您可以考虑将日期解析为datetime.date对象,并将其用作defaultdict的键。然后,您可以按键排序并按日期/时间按顺序获取所有项目 - 无论它们在源文本文件中的显示顺序如何。

正如@ user2357112在注释中指出的那样,在递增计数器时可以使逻辑更简单。像这样:

counter = OrderedDict()

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] = counter.get(day, 0) + 1

答案 1 :(得分:0)

您可以定义自己的类,该类继承自$days_of_week = array(); $week_number = 21; $year = date('Y'); for($day = 0; $day <= 6; $day++) { $format = $year. "W" . $week_number.$day; print $format . "\n"; array_push($days_of_week, date('Y-m-d', strtotime($format))); } print_r($days_of_week); defaultdict

OrderedDict
相关问题