comparison flatten_lines.py @ 319:c58cd7e48db7

begin to switch settable to TextLineList
author catherine@dellzilla
date Thu, 11 Feb 2010 13:07:05 -0500
parents f44ad8de0d17
children b9f19255d4b7
comparison
equal deleted inserted replaced
318:f44ad8de0d17 319:c58cd7e48db7
1 import doctest 1 import doctest
2 def flatten(texts): 2
3 class TextLineList(list):
4 '''A list that "wants" to consist of separate lines of text.
5 Splits multi-line strings and flattens nested lists to
6 achieve that.
7 Also omits blank lines, strips leading/trailing whitespace.
8
9 >>> tll = TextLineList(['my', 'dog\\nhas', '', [' fleas', 'and\\nticks']])
10 >>> tll
11 ['my', 'dog', 'has', 'fleas', 'and', 'ticks']
12 >>> tll.append(['and', ['spiders', 'and']])
13 >>> tll
14 ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and']
15 >>> tll += 'fish'
16 >>> tll
17 ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and', 'fish']
3 ''' 18 '''
4 >>> flatten([['cow', 'cat'], '', 'fish', ['bird']]) 19 def flattened(self, texts):
5 ['cow', 'cat', 'fish', 'bird'] 20 result = []
6 ''' 21 if isinstance(texts, basestring):
7 result = [] 22 result.extend(texts.splitlines())
8 if isinstance(texts, basestring): 23 else:
9 result.extend(texts.splitlines()) 24 for text in texts:
10 else: 25 result.extend(self.flattened(text))
11 for text in texts: 26 result = [r.strip() for r in result if r.strip()]
12 result.extend(flatten(text)) 27 return result
13 result = [r.strip() for r in result if r.strip()] 28 def flatten(self):
14 return result 29 list.__init__(self, self.flattened(self))
30 def __init__(self, values):
31 list.__init__(self, values)
32 self.flatten()
33 def append(self, value):
34 list.append(self, value)
35 self.flatten()
36 def extend(self, values):
37 list.extend(self, values)
38 self.flatten()
39 def __setitem__(self, idx, value):
40 list.__setitem__(self, idx, value)
41 self.flatten()
42 def __iadd__(self, value):
43 if isinstance(value, basestring):
44 self.append(value)
45 else:
46 list.__iadd__(self, value)
47 self.flatten()
48 return self
49
15 doctest.testmod() 50 doctest.testmod()
16
17 class LineList(list):
18 def __add__(self, newmember):
19