Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple text manipulation in python
class indented_line:
def __init__(self, line):
self.line = line.lstrip('\t')
self.tabs = len(line) - len(self.line)
def indent(self, indention):
return indented_line('\t'*(self.tabs + indention) + self.line)
@property
def stripped(self):
return self.line.strip()
def __bool__(self):
return bool(self.stripped)
def replace(self, find, replace):
return indented_line('\t'*(self.tabs) + self.line.replace(find, replace))
def get_indented_block(data):
if isinstance(data, indented_block):
return data
else:
return indented_block(data)
class indented_block:
def __init__(self, data=None):
if data == None:
self.block = list()
elif isinstance(data, str):
self.block = list(indented_line(l) for l in data.split('\n'))
elif isinstance(data, list):
self.block = list()
for item in data:
if isinstance(item, indented_line):
self.block.append(item)
elif isinstance(item, indented_block):
self.block += list(item)
elif isinstance(item, str):
self.block.append(indented_line(item))
else:
raise TypeError(item)
else:
raise TypeError(data)
def __add__(self, other):
return indented_block(self.block + get_indented_block(other).block)
def indent(self, indention):
return indented_block([l.indent(indention) for l in self])
def to_text(self, tab='\t'):
return '\n'.join(tab * l.tabs + l.line for l in self)
def __len__(self):
return len(self.block)
def __iter__(self):
yield from self.block
@property
def first_line(self):
for line in self:
if line:
return line
@property
def last_line(self):
for line in reversed(list(self)):
if line:
return line
def __repr__(self):
beginning = self.first_line.stripped[:10]
end = self.last_line.stripped[-10:]
return "<%s %il '%s'…'%s'>" % (self.__class__.__name__, len(self), beginning, end)
def replace(self, find, replace):
assert isinstance(find, str)
r = get_indented_block(replace)
if len(r) > 1: #Replace line with data
return indented_block([r.indent(l.tabs) if l.stripped == find else l for l in self])
elif len(r) == 1: #replace word with line
return indented_block([l.replace(find, r.to_text()) for l in self])
else:
raise TypeError(r)
def replace_kw(self, **replacement_dict):
result = indented_block(self.block)
for find, replace in replacement_dict.items():
result = result.replace(find, replace)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment