You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.3 KiB
55 lines
1.3 KiB
import click |
|
import pyperclip |
|
|
|
|
|
def split_table(text): |
|
rows = [] |
|
for line in text.splitlines(): |
|
values = line.split("\t") |
|
cells = [v.strip() for v in values] |
|
rows.append(cells) |
|
return rows |
|
|
|
|
|
def get_cell_lengths(table): |
|
tmp = {} |
|
|
|
for row in table: |
|
for i, cell in enumerate(row): |
|
if i not in tmp: |
|
tmp[i] = [] |
|
tmp[i].append(len(cell)) |
|
|
|
return {k: max(v) for k, v in tmp.items()} |
|
|
|
|
|
def build_table(table, lengths): |
|
text_rows = [_build_row(row, lengths) for row in table] |
|
header, *rest = text_rows |
|
sep_items = ["-" * lengths[k] for k in sorted(lengths.keys())] |
|
separator = _build_line(sep_items) |
|
lines = [header, separator] + rest |
|
return "\r\n".join(lines) |
|
|
|
|
|
def _build_row(row, lengths): |
|
items = [] |
|
for i, cell in enumerate(row): |
|
length = lengths[i] |
|
items.append(cell.ljust(length)) |
|
return _build_line(items) |
|
|
|
|
|
def _build_line(items): |
|
tmp = " | ".join(items) |
|
return f"| {tmp} |" |
|
|
|
|
|
@click.command() |
|
def cli(): |
|
xls = pyperclip.paste() |
|
table = split_table(xls) |
|
lengths = get_cell_lengths(table) |
|
result = build_table(table, lengths) |
|
print("copied to clipboard") |
|
pyperclip.copy(result)
|
|
|