Last active
March 23, 2018 00:15
-
-
Save jamespeterschinner/cfb2b4efd8254a7b581fda5e23bca305 to your computer and use it in GitHub Desktop.
Nice Character array wrapper
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
import numpy as np | |
def horizontal_index(n, offset=0): | |
"""Create horizontal index with vertically aligned numbers""" | |
index = [' ' * offset for _ in range(len(str(n)))] | |
for number in map(str, range(n)): | |
for idx, n in enumerate(number): | |
index[idx] += n + '|' | |
pad = max(map(len, index)) | |
return '\n'.join(i.rjust(pad, ' ') for i in reversed(index)) | |
def vertical_index(n): | |
"""Generate row numbers for an index""" | |
width = len(str(n)) | |
index = map(str, range(n)) | |
for ind in (i.rjust(width, ' ') + '|' for i in index): | |
yield '\n' + ind | |
class TextArray(object): | |
def __init__(self, text): | |
# Pad out each row to the max len row | |
rows = text.split('\n') | |
max_len = max(map(len, rows)) | |
self.array = np.array([list(str(row).ljust(max_len, ' ')) for row in rows]) | |
def __getitem__(self, index): | |
row, column = index | |
return self.array[row, column] | |
def __setitem__(self, key, value): | |
row, column = key | |
self.array[row, column] = value | |
def __repr__(self): | |
"""Create a nice console display""" | |
row_index = vertical_index(self.array.shape[0]) | |
column_index = horizontal_index(self.array.shape[1], len(str(self.array.shape[0])) + 1) | |
result = ''.join(row + ' '.join(self.array[idx]) for idx, row in enumerate(row_index)) | |
return f'{column_index}' \ | |
f'{result}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TextArray
is a nice way to work with text data that is structured in a grid.Demo:
ASCII art from https://www.asciiart.eu/animals/bisons