Skip to content

Instantly share code, notes, and snippets.

@suricactus
Created December 20, 2022 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suricactus/91f7a06a0fbb6bdee9de09ba5cc4cef3 to your computer and use it in GitHub Desktop.
Save suricactus/91f7a06a0fbb6bdee9de09ba5cc4cef3 to your computer and use it in GitHub Desktop.
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