def build_command_groups(self, block): """ Creates block modification commands, grouped by start index, with the text to apply them on. """ text = block.get('text') commands = self.build_commands(block) # Tried using itertools.tee but for some reason that failed. Oh well. grouped = Command.grouped_by_index(commands) listed = list(Command.grouped_by_index(commands)) sliced = [] i = 0 for start_index, commands in grouped: next_group = listed[i + 1] if i + 1 < len(listed) else False stop_index = next_group[0] if next_group else 0 sliced.append((text[start_index:stop_index], list(commands))) i += 1 return sliced
def test_grouped_by_index(self): grouped = Command.grouped_by_index([ Command('start_text', 0), Command('stop_text', 19), Command('start_inline_style', 0, 'ITALIC'), Command('stop_inline_style', 4, 'ITALIC'), Command('start_inline_style', 9, 'BOLD'), Command('stop_inline_style', 12, 'BOLD'), Command('start_entity', 5, 0), Command('stop_entity', 14, 0), Command('start_entity', 0, 1), Command('stop_entity', 4, 1), ]) flattened = [(index, list(group)) for index, group in grouped] self.assertEqual(str(flattened), str([ (0, [ Command('start_text', 0), Command('start_inline_style', 0, 'ITALIC'), Command('start_entity', 0, 1), ]), (4, [ Command('stop_inline_style', 4, 'ITALIC'), Command('stop_entity', 4, 1), ]), (5, [ Command('start_entity', 5, 0), ]), (9, [ Command('start_inline_style', 9, 'BOLD'), ]), (12, [ Command('stop_inline_style', 12, 'BOLD'), ]), (14, [ Command('stop_entity', 14, 0), ]), (19, [ Command('stop_text', 19), ]), ]))