Skip to content

Instantly share code, notes, and snippets.

@averrin
Created May 10, 2012 14:50
Show Gist options
  • Save averrin/2653663 to your computer and use it in GitHub Desktop.
Save averrin/2653663 to your computer and use it in GitHub Desktop.
s = {
'tag': '<span class="boom"></span>',
'content':
[
'Server status: ',
{
'tag': '<a></a>',
'content':
[
'[online]',
{
'tag': '<b></b>',
'content': ['!!!']
}
]
},
'<br>',
{
'tag': '<span class="foo"></span>',
'content': ['Done']
}
]
}
class node(object):
def __init__(self, line):
t = line['tag'].find('><') + 1
self.open_tag = line['tag'][:t]
self.close_tag = line['tag'][t:]
self._content = line['content']
self.current_pos = 0
self.chars_out = 0
def process(self):
content = ''
n = 0
for part in self._content:
if n < self.current_pos:
if type(part) == str:
sub_content = part[:self.current_pos - n]
content += sub_content
n += len(sub_content)
else:
child = node(part)
child.current_pos = self.current_pos - n
content += child.process()
n += child.chars_out
self.chars_out = n
return self.open_tag + content + self.close_tag
def __len__(self):
foo = lambda c: sum(len(x) if type(x) is str else foo(x['content']) for x in c)
return foo(self._content)
def main():
n = node(s)
for t in xrange(len(n)):
print n.process()
n.current_pos += 1
print n.process()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment