#!/usr/bin/python """ Sentence: A class for constructing and deconstructing text for NIPyLL lexicons. Sentences can be constructed from strings, or built by in-place addition of strings. A built sentence can be iterated over, word by word. Includes self-test. You are free to use, modify or distribute this program under the terms of the GNU General Public License: http://www.gnu.org/copyleft/gpl.html Author: Chris Reece See also: http://www.jessies.org/~car/projects/nipyll/ """ import re class Sentence: nonWordsRE = re.compile('\W+') words = [] def __init__(self, other = None): self.words = [] if other == None: return self += other def __del__(self): pass def __iadd__(self, other): if other.__class__ == list: string = ' '.join(other) elif other.__class__ == str: string = other else: string = str(other) string = string.lower() string = Sentence.nonWordsRE.sub(' ', string) newWords = string.split() self.words += newWords return self def __getitem__(self, i): return self.words[i] def __str__(self): return ' '.join(self.words) def __repr__(self): return 'words = ' + str(self.words) if __name__ == '__main__': for i in xrange(3): print 'SELF-TEST LOOP', i s = Sentence('This is Sentence\'s test sentence') print '__class__\n\t', print s.__class__ print '__str__\n\t', print str(s) print '__repr__\n\t', print repr(s) print '__iadd__\n\t', s += 'plus' print s, '\n\t', s += ['more', 'and'] print s, '\n\t', s += 'more words' print s print '__getitem__\n\t', for w in s: print w, '\n\t', print del s