Created
March 14, 2011 04:05
-
-
Save e000/868745 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from texttable import Texttable | |
import re | |
_ignParens = re.compile('\(.*?\)') | |
def countDelim(text, delim = ' | '): | |
text = _ignParens.sub('', text) # get rid of the stuff inside of parens when searching for ' | ' | |
return text.count(delim) | |
def renderTable(input, sub = False): | |
input = input[:] # make a copy of the input, so it doesn't eat the one in the cache. | |
if not input: | |
return [] # input is not sane. | |
if len(input) == 1 and sub: # we're a subtable, if we're just one line, don't make a subtable out of it. | |
return input | |
garbage = [] # stuff to add to the end that didn't belong. | |
initial_row_count = countDelim(input[0]) # how many rows is the header | |
if initial_row_count >= 5: # header is really big, fuck it. | |
return input | |
t = Texttable(100) # our table | |
while input: | |
line = input.pop(0) # get the top line | |
rCount = countDelim(line) # how many ' | ' exist in the line. | |
if rCount == 0: | |
garbage.append(line) # it's not a row, it's garbage. | |
else: | |
rows = line.split(' | ', initial_row_count) # split it into rows | |
sub_row_count = countDelim(rows[-1]) # do we have any other rows? if so we've got a subtable. | |
if sub_row_count > 0: | |
if len(input) > 1 and countDelim(input[1]) == sub_row_count: # does the next line in the table match our count, then we've definately got a subtable | |
buf = [rows[-1]] # start our smaller subtable input | |
while input: | |
line = input.pop(0) | |
if countDelim(line) != sub_row_count: # woah, the row counts no longer line up... we're done | |
input.insert(0, line) # put this line back. | |
break | |
buf.append(line) # this line is part of our table | |
rows[-1] = '\n'.join(renderTable(buf, True)) # render our subtable. | |
t.add_row([utf8(row) for row in rows]) # add our row to table | |
draw = t.draw() # draw | |
if not draw: # if the table is empty, it'll return None, rarely happens, sometimes it does though, and I'm not quite sure why. | |
draw = [] | |
else: | |
draw = draw.split('\n') | |
return draw + garbage # tack the garbage onto the end, and return it. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment