1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/simplex/accessors.py Sat Oct 01 19:33:58 2011 +0200
1.3 @@ -0,0 +1,63 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Accessor classes for indexing.
1.8 +
1.9 +Copyright (C) 2011 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT ANY
1.17 +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
1.18 +PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.19 +
1.20 +You should have received a copy of the GNU General Public License along
1.21 +with this program. If not, see <http://www.gnu.org/licenses/>.
1.22 +"""
1.23 +
1.24 +class DelimitedRecord:
1.25 +
1.26 + "An accessor using a delimiter to split a record."
1.27 +
1.28 + def __init__(self, keys=None, delimiter=None, numeric=0):
1.29 +
1.30 + """
1.31 + Initialise the accessor using a sequence of 'keys' indicating the
1.32 + columns in each record that provide the values in the eventual compound
1.33 + key provided by each record, along with a 'delimiter' indicating how
1.34 + such columns are identified. If 'numeric' is set to a true value, keys
1.35 + will be interpreted as numbers.
1.36 + """
1.37 +
1.38 + self.keys = keys or [0]
1.39 + self.delimiter = delimiter
1.40 + self.numeric = numeric
1.41 +
1.42 + # Define a conversion method.
1.43 +
1.44 + self.convert = numeric and self.convert_numeric or (lambda x: x)
1.45 +
1.46 + def convert_numeric(self, term):
1.47 + return map(int, term)
1.48 +
1.49 + def get_key(self, record):
1.50 + values = record.split(self.delimiter)
1.51 + return self.convert([values[key] for key in self.keys])
1.52 +
1.53 + def get_sort_command(self):
1.54 +
1.55 + """
1.56 + Return the Unix sort command invocation required to produce the ordering
1.57 + described by this instance.
1.58 + """
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.numeric and " -n" or "",
1.63 + "".join([(" -k %d,%d" % (key + 1, key + 1)) for key in self.keys])
1.64 + )
1.65 +
1.66 +# vim: tabstop=4 expandtab shiftwidth=4