Created
December 20, 2022 12:53
-
-
Save suricactus/91f7a06a0fbb6bdee9de09ba5cc4cef3 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
import sys | |
from typing import List | |
reset_color = "\033[0m" | |
colors = [ | |
"\033[91m", # red | |
"\033[92m", # green | |
"\033[93m", # yellow | |
"\033[94m", # blue | |
"\033[95m", # purple | |
"\033[96m", # cyan | |
] | |
colors_count = len(colors) | |
def colorize_line(line: str, separators: List[str], quoted: bool) -> str: | |
is_quoting = False | |
chars = colors[0] | |
idx = 1 | |
for char in line: | |
if char in ('"', "'") and quoted: | |
is_quoting = not is_quoting | |
if char in separators and not is_quoting: | |
chars += reset_color | |
chars += char | |
chars += colors[idx % colors_count] | |
idx += 1 | |
else: | |
chars += char | |
chars += reset_color | |
return chars | |
def main(file: str, separators: str, quoted: bool) -> None: | |
separators_str = separators | |
separators = [] | |
if separators_str == ",": | |
separators = [","] | |
else: | |
if ",," in separators_str: | |
separators_str = separators_str.replace(",,", "") | |
separators.append(",") | |
separators += separators_str.split(",") | |
for line in file: | |
colorized_line = colorize_line(line, separators, quoted) | |
print(colorized_line, end="", flush=True) | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"file", nargs="?", type=argparse.FileType("r"), default=sys.stdin | |
) | |
parser.add_argument( | |
"-s", | |
"--separators", | |
help="Separators delimited by a comma. Default: \\t", | |
default="\t", | |
) | |
parser.add_argument("-q", "--quoted", action="store_true") | |
args = parser.parse_args() | |
main(args.file, separators=args.separators, quoted=args.quoted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment