Created
February 6, 2018 11:01
-
-
Save katrielalex/3f65dd050c407ab53300a33ad4490f8f to your computer and use it in GitHub Desktop.
Print strings colored by character frequency
This file contains hidden or 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
#!/usr/bin/env python3 | |
from itertools import accumulate, chain, repeat, tee | |
import click | |
import collections | |
import crayons | |
import split | |
COLORS = "red yellow blue white".split() | |
# http://wordaligned.org/articles/slicing-a-list-evenly-with-python | |
def chunk(xs, n): | |
assert n > 0 | |
L = len(xs) | |
s, r = divmod(L, n) | |
widths = chain(repeat(s+1, r), repeat(s, n-r)) | |
offsets = accumulate(chain((0,), widths)) | |
b, e = tee(offsets) | |
next(e) | |
return [xs[s] for s in map(slice, b, e)] | |
@click.command() | |
@click.argument('s') | |
def main(s): | |
n = len(COLORS) | |
freqs = collections.Counter(s) | |
chunks = chunk(list(freqs), n) | |
assert n == len(chunks) # sanity check | |
# index of the frequency bucket containing a character | |
freq_bucket = lambda c: min(i for i, chunk in enumerate(chunks) if c in chunk) | |
colored = lambda c: getattr(crayons, COLORS[freq_bucket(c)])(c) | |
for c in s: | |
print(colored(c), end='') | |
print() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment