Skip to content

Instantly share code, notes, and snippets.

@odanado
Forked from ihsgnef/colorize_text.py
Created November 21, 2017 13:20
Show Gist options
  • Save odanado/b9e9b2bb9f1a2fa7938b666ba1794d10 to your computer and use it in GitHub Desktop.
Save odanado/b9e9b2bb9f1a2fa7938b666ba1794d10 to your computer and use it in GitHub Desktop.
Visualize attention over text with background colors
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def colorize(words, color_array):
# words is a list of words
# color_array is an array of numbers between 0 and 1 of length equal to words
cmap = matplotlib.cm.get_cmap('RdBu')
template = '<span class="barcode"; style="color: black; background-color: {}">{}</span>'
colored_string = ''
for word, color in zip(words, color_array):
color = matplotlib.colors.rgb2hex(cmap(color)[:3])
colored_string += template.format(color, '&nbsp' + word + '&nbsp')
return colored_string
words = 'The quick brown fox jumps over the lazy dog'.split()
color_array = np.random.rand(len(words))
s = colorize(words, color_array)
# to display in ipython notebook
from IPython.display import display, HTML
display(HTML(s))
# or simply save in an html file and open in browser
with open('colorize.html', 'w') as f:
f.write(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment