1.1 --- a/simplex/accessors.py Sat Oct 01 20:49:15 2011 +0200
1.2 +++ b/simplex/accessors.py Sat Oct 01 22:06:03 2011 +0200
1.3 @@ -18,50 +18,59 @@
1.4 with this program. If not, see <http://www.gnu.org/licenses/>.
1.5 """
1.6
1.7 -class DelimitedRecord:
1.8 +class Accessor:
1.9 +
1.10 + "An abstract accessor."
1.11 +
1.12 + def reset(self):
1.13 + pass
1.14 +
1.15 + def convert(self, term):
1.16 + return term
1.17 +
1.18 + def get_key(self, record):
1.19 + return record
1.20 +
1.21 +class DelimitedRecord(Accessor):
1.22
1.23 "An accessor using a delimiter to split a record."
1.24
1.25 - def __init__(self, keys=None, delimiter=None, converter=None):
1.26 + def __init__(self, fields=None, delimiter=None):
1.27
1.28 """
1.29 - Initialise the accessor using a sequence of 'keys' indicating the
1.30 + Initialise the accessor using a sequence of 'fields' indicating the
1.31 columns in each record that provide the values in the eventual compound
1.32 key provided by each record, along with a 'delimiter' indicating how
1.33 - such columns are identified. If 'converter' is specified, this will be
1.34 - used to convert the retrieved data.
1.35 + such columns are identified.
1.36 """
1.37
1.38 - self.keys = keys or [0]
1.39 + self.fields = fields or [0]
1.40 self.delimiter = delimiter
1.41 - self.converter = converter
1.42 - self.convert = converter and converter.convert or (lambda x: x)
1.43
1.44 def get_key(self, record):
1.45 values = record.split(self.delimiter)
1.46 - return self.convert([values[key] for key in self.keys])
1.47 + return [values[field] for field in self.fields]
1.48
1.49 - def get_sort_command(self):
1.50 +class Converted(Accessor):
1.51
1.52 - """
1.53 - Return the Unix sort command invocation required to produce the ordering
1.54 - described by this instance.
1.55 - """
1.56 + "Conversion of keys."
1.57 +
1.58 + def __init__(self, accessor, converters=None):
1.59
1.60 - return "sort%s%s%s" % (
1.61 - self.delimiter and (" -t $'%s'" % repr(self.delimiter)[1:-1]) or "",
1.62 - self.converter and self.converter.get_sort_options() or "",
1.63 - "".join([(" -k %d,%d" % (key + 1, key + 1)) for key in self.keys])
1.64 - )
1.65 + "Wrap the given 'accessor' with the given 'converters'."
1.66
1.67 -class ConvertNumeric:
1.68 + self.accessor = accessor
1.69 + self.converters = converters
1.70
1.71 - "Convert numeric values to integers."
1.72 + def get_converter(self, converter):
1.73 + return converter or (lambda x: x)
1.74
1.75 def convert(self, term):
1.76 - return map(int, term)
1.77 + converters = map(self.get_converter, self.converters)
1.78 + return [converter(value) for converter, value in zip(converters, term)]
1.79
1.80 - def get_sort_options(self):
1.81 - return " -n"
1.82 + def get_key(self, record):
1.83 + key = self.accessor.get_key(record)
1.84 + return self.convert(key)
1.85
1.86 # vim: tabstop=4 expandtab shiftwidth=4