gpt4 book ai didi

python - 使用 OrderedDict 对实例进行计数

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:14 24 4
gpt4 key购买 nike

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

最佳答案

您可以检查 OrderedDict 中是否有 day。如果是,则添加到它,如果没有,则将其设置为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

关于python - 使用 OrderedDict 对实例进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com