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 Accessor: 22 23 "An abstract accessor." 24 25 def reset(self): 26 pass 27 28 def convert(self, term): 29 return term 30 31 def get_key(self, record): 32 return record 33 34 class DelimitedRecord(Accessor): 35 36 "An accessor using a delimiter to split a record." 37 38 def __init__(self, fields=None, delimiter=None): 39 40 """ 41 Initialise the accessor using a sequence of 'fields' indicating the 42 columns in each record that provide the values in the eventual compound 43 key provided by each record, along with a 'delimiter' indicating how 44 such columns are identified. 45 """ 46 47 self.fields = fields or [0] 48 self.delimiter = delimiter 49 50 def get_key(self, record): 51 values = record.split(self.delimiter) 52 return [values[field] for field in self.fields] 53 54 class Converted(Accessor): 55 56 "Conversion of keys." 57 58 def __init__(self, accessor, converters=None): 59 60 "Wrap the given 'accessor' with the given 'converters'." 61 62 self.accessor = accessor 63 self.converters = converters 64 65 def get_converter(self, converter): 66 return converter or (lambda x: x) 67 68 def convert(self, term): 69 converters = map(self.get_converter, self.converters) 70 return [converter(value) for converter, value in zip(converters, term)] 71 72 def get_key(self, record): 73 key = self.accessor.get_key(record) 74 return self.convert(key) 75 76 # vim: tabstop=4 expandtab shiftwidth=4