Created
March 6, 2017 07:20
-
-
Save inakagawa/efeaa124feaf0cddb9623051dec580bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# hierarchical lines | |
class HierLines: | |
def __init__(self): | |
self.current_rank = 0 | |
self.data = [] | |
self.current_cursor = self.data | |
self.cursor_stack = [] | |
self.cursor_stack.append(self.current_cursor) | |
def add_line(self,text,rank, fn=None): | |
if(rank > self.current_rank): | |
self.descend_until(rank) | |
elif(rank < self.current_rank): | |
self.ascend_until(rank) | |
ld = LineData(text) | |
self.current_cursor.append(ld) | |
def descend_until(self, rank): | |
while rank > self.current_rank: | |
# 今のcursor をスタックに退避 | |
# 新しいcursor を作る | |
self.cursor_stack.append(self.current_cursor) | |
new_cursor = [] | |
self.current_cursor.append(new_cursor) | |
self.current_cursor = new_cursor | |
self.current_rank += 1 | |
def ascend_until(self, rank): | |
while rank < self.current_rank: | |
self.current_cursor = self.cursor_stack.pop() | |
self.current_rank -= 1 | |
def get_raw_data(self): | |
return self.data | |
def get_flat_data(self, D=None, F=None): | |
result = [] | |
if( not F ): | |
F = lambda O: str(O) | |
if( not D): | |
D = self.data | |
if isinstance(D, list): | |
for DI in D: | |
result += self.get_flat_data(DI,F) | |
return result | |
else: | |
result.append(F(D)) | |
return result | |
class LineData: | |
def __init__(self, text, modifier=None): | |
# modifier: | |
self.text = text | |
self.modifier = modifier | |
def __str__(self): | |
if(self.modifier): | |
return self.modifier(self) | |
else: | |
return self.text | |
hl = HierLines() | |
hl.add_line('a',1) | |
hl.add_line('b',2) | |
hl.add_line('c',3, (lambda x: x+'/')) | |
hl.add_line('d',1) | |
hl.add_line('e',3) | |
print(hl.get_raw_data()) | |
print(hl.get_flat_data()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment