add FallbackCounter class used with Python 2.6 since collections.Counter was added in Python 2.7

This commit is contained in:
Jeremy Carbaugh 2012-03-14 00:01:10 -07:00
parent adf665fcaa
commit 984b1b6550
2 changed files with 24 additions and 1 deletions

View File

@ -1,4 +1,5 @@
from saucebrush.filters import Filter
from saucebrush.utils import FallbackCounter
import collections
import itertools
import math
@ -193,7 +194,10 @@ class Histogram(StatsFilter):
def __init__(self, field, **kwargs):
super(Histogram, self).__init__(field, **kwargs)
self._counter = collections.Counter()
if hasattr(collections, 'Counter'):
self._counter = collections.Counter()
else:
self._counter = FallbackCounter()
def process_field(self, item):
self._counter[self.prep_field(item)] += 1

View File

@ -1,3 +1,4 @@
import collections
import os
try:
@ -62,6 +63,24 @@ def str_or_list(obj):
# utility classes
#
class FallbackCounter(collections.defaultdict):
""" Python 2.6 does not have collections.Counter.
This is class that does the basics of what we need from Counter.
"""
def __init__(self, *args, **kwargs):
super(FallbackCounter, self).__init__(int)
def most_common(n=None):
l = sorted(self.items(),
cmp=lambda x,y: cmp(x[1], y[1]))
if n is not None:
l = l[:n]
return l
class Files(object):
""" Iterate over multiple files as a single file. Pass the paths of the
files as arguments to the class constructor: