1 #!/usr/bin/env python 2 3 """ 4 Reader and 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 TextFile: 22 23 """ 24 An example wrapper around text files, mostly duplicating the facilities of 25 file objects itself. 26 """ 27 28 def __init__(self, f): 29 self.f = f 30 31 def seek(self, pos): 32 self.f.seek(pos) 33 34 def __iter__(self): 35 return iter(self.f.xreadlines()) 36 37 class DelimitedRecord: 38 39 "An accessor using a delimiter to split a record." 40 41 def __init__(self, fields=None, delimiter=None, numeric=0): 42 43 """ 44 Initialise the accessor using a sequence of 'fields' indicating the 45 columns in each record that provide the values in the eventual compound 46 field provided by each record, along with a 'delimiter' indicating how 47 such columns are identified. If 'numeric' is set to a true value, fields 48 will be interpreted as numbers. 49 """ 50 51 self.fields = fields or [0] 52 self.delimiter = delimiter 53 self.convert = numeric and self.convert_numeric or (lambda x: x) 54 55 def convert_numeric(self, term): 56 return map(int, term) 57 58 def get_key(self, record): 59 values = record.split(self.delimiter) 60 return self.convert([values[field] for field in self.fields]) 61 62 # vim: tabstop=4 expandtab shiftwidth=4