1 #!/usr/bin/env python 2 3 """ 4 Accessor classes for indexing. 5 6 Copyright (C) 2011 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 class DelimitedRecord: 22 23 "An accessor using a delimiter to split a record." 24 25 def __init__(self, keys=None, delimiter=None, converter=None): 26 27 """ 28 Initialise the accessor using a sequence of 'keys' indicating the 29 columns in each record that provide the values in the eventual compound 30 key provided by each record, along with a 'delimiter' indicating how 31 such columns are identified. If 'converter' is specified, this will be 32 used to convert the retrieved data. 33 """ 34 35 self.keys = keys or [0] 36 self.delimiter = delimiter 37 self.converter = converter 38 self.convert = converter and converter.convert or (lambda x: x) 39 40 def get_key(self, record): 41 values = record.split(self.delimiter) 42 return self.convert([values[key] for key in self.keys]) 43 44 def get_sort_command(self): 45 46 """ 47 Return the Unix sort command invocation required to produce the ordering 48 described by this instance. 49 """ 50 51 return "sort%s%s%s" % ( 52 self.delimiter and (" -t $'%s'" % repr(self.delimiter)[1:-1]) or "", 53 self.converter and self.converter.get_sort_options() or "", 54 "".join([(" -k %d,%d" % (key + 1, key + 1)) for key in self.keys]) 55 ) 56 57 class ConvertNumeric: 58 59 "Convert numeric values to integers." 60 61 def convert(self, term): 62 return map(int, term) 63 64 def get_sort_options(self): 65 return " -n" 66 67 # vim: tabstop=4 expandtab shiftwidth=4