Last active
November 13, 2015 14:22
-
-
Save dazfuller/9a23af1cd2b4f9b25c5f 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 -*- | |
import argparse | |
def reformat_table(content, start, end): | |
tabledata = [line.split(" | ") for line in content[start:end]] | |
tabledata.pop(1) | |
lengths = [0] * len(tabledata[0]) | |
for row in tabledata: | |
lengths = map( | |
lambda pair: max(pair), | |
zip(lengths, [len(cell) for cell in row]) | |
) | |
newtable = [] | |
for row in tabledata: | |
newtable.append( | |
" | ".join( | |
[cell.ljust(lengths[i]) for i, cell in enumerate(row)] | |
) | |
) | |
newtable[1:1] = [" | ".join(["-" * l for l in lengths])] | |
content[start:end] = newtable | |
def clean_tables(content): | |
start = 0 | |
end = 0 | |
for i, line in enumerate(content): | |
if "- |" in line: # Find the component which defines a table | |
start = i - 1 | |
elif start != 0 and " |" not in line: | |
end = i | |
reformat_table(content, start, end) | |
start = 0 | |
end = 0 | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="This is an example cleanup script") | |
parser.add_argument("-f", "--file", metavar="File", type=argparse.FileType("r"), dest="file", required=True, help="Specifies the file to be cleaned") | |
args = parser.parse_args() | |
content = [line.rstrip() for line in args.file] | |
clean_tables(content) | |
for line in content: | |
print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example for creating a script to cleanup Markdown files to ensure that tables are consistently formatted. Tested with Python 2.7.10