Created
November 1, 2019 18:43
-
-
Save stephenroller/090172120924f13eed2ab9003367de00 to your computer and use it in GitHub Desktop.
Reformats latex tables so columns align
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
#!/usr/bin/env python | |
import sys | |
data = sys.stdin.read() | |
lines = data.split('\n') | |
columnized = [ | |
x.replace(r'\\[-0.25mm]', '').replace(r'\\', '').split('&') for x in lines | |
] | |
lengths = [] | |
outrows = [] | |
numcolumns = max(len(row) for row in columnized) | |
for i, row in enumerate(columnized): | |
if len(row) != numcolumns: | |
outrows.append(lines[i]) | |
continue | |
newrow = [' ' + c.strip() + ' ' for c in row] | |
outrows.append(newrow) | |
for i, c in enumerate(newrow): | |
if len(lengths) <= i or lengths[i] < len(c): | |
if len(lengths) <= i: | |
lengths.append(None) | |
lengths[i] = len(c) | |
finalrows = [] | |
for r, row in enumerate(outrows): | |
if type(row) is str: | |
print(row) | |
continue | |
fr = [] | |
for i, c in enumerate(row): | |
formatstr = "%-" + str(lengths[i]) + "s" | |
fr.append(formatstr % (c)) | |
print("&".join(fr) + r'\\') | |
if r == 0: | |
print(r'\midrule') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
input:
output: