Python 使用OrderedDict计算实例数
我试图使用OrderedDict()来跟踪单词的实例。我有按天组织的数据,我想计算当天“foo”的实例数。每行都按天编制索引。使用defaultdict可以满足我的需求,但是,当然,不需要订购:Python 使用OrderedDict计算实例数,python,counter,ordereddictionary,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], lin
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)
您可以定义自己的类,该类继承自
defaultdict
和orderedict
class OrderedDefaultDict(defaultdict, OrderedDict):
def __init__(self, default, *args, **kwargs):
defaultdict.__init__(self, default)
OrderedDict.__init__(self, *args, **kwargs)
counter = OrderedDefaultDict(int)
您可以检查
日期
是否在OrderedICT中。如果是,则添加到它,如果不是,则将其设置为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将在源文本文件中每天第一次出现时进行排序
相反,您可以考虑将日期解析为DATETME.DATE对象,并将其作为Debug语句上的键。然后,您可以按键排序,并按日期/时间按顺序获取所有项目,而不管它们在源文本文件中的显示顺序如何
正如@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
或者
counter[day]=counter.get(day,0)+1
@user2357112搞定了!好的呼叫@user2357112。不知道为什么我自己不这么想。我已经更新了答案并给了你信任。我不推荐这样做。defaultdict
和orderedict
都不是为多重继承而设计的。我看到您试图通过多次初始化来解决问题,但它仍然比仅仅继承orderedict
并提供您自己的\uuu missing\uu
方法要脆弱得多。