Paste #37

  • #37
  1. #!/usr/bin/python
  2. """Read a vim colorscheme and output an HTML file containing all colors."""
  3.  
  4. import re
  5. import sys
  6.  
  7.  
  8. HEX_REGEX = re.compile(r'#[a-fA-F\d]{6}')
  9.  
  10.  
  11. def main():
  12.     colorscheme = sys.argv[1]
  13.     colorscheme_hexes = list()
  14.  
  15.     with open(colorscheme) as colorscheme_file:
  16.         for line in colorscheme_file:
  17.             matches = HEX_REGEX.findall(line)
  18.             [colorscheme_hexes.append(match) for match in matches
  19.              if match not in colorscheme_hexes]
  20.  
  21.     html = "<html><title>{0} colorscheme</title><body>".format(colorscheme)
  22.     html += "<table><tr>"
  23.  
  24.     for (counter, color) in enumerate(colorscheme_hexes):
  25.         if (counter % 5 == 0):
  26.             html += '</tr><tr>'
  27.         text_color = get_text_color(color)
  28.         html += ('<td style="width:100px;height:100px;background-color:{0};'
  29.                  'color:{1};text-align:center;">'.format(color, text_color))
  30.         html += color
  31.         html += "</td>"
  32.  
  33.     html += "</tr></table>"
  34.     html += "</body></html>"
  35.  
  36.     with open('./output.html', 'w') as out_file:
  37.         out_file.write(html)
  38.  
  39.  
  40. def get_text_color(hex_color_code):
  41.     """Use black for light colors and white for dark ones."""
  42.     (red, green, blue) = rgb_from_hex(hex_color_code)
  43.     luminance = (0.299 * red + 0.587 * green + 0.114 * blue) / 255
  44.     if luminance < 0.5:
  45.         return "#FFFFFF"
  46.     else:
  47.         return "#000000"
  48.  
  49.  
  50. def rgb_from_hex(hex_color_code):
  51.     """Return the RGB tuple of the hex color."""
  52.     color_numbers = hex_color_code[1:]
  53.     red = int(color_numbers[:2], 16)
  54.     green = int(color_numbers[2:4], 16)
  55.     blue = int(color_numbers[4:], 16)
  56.     return (red, green, blue)
  57.  
  58.  
  59. def usage():
  60.     print("A single argument is required: python2 vim_color_palette.py file")
  61.  
  62.  
  63. if __name__ == '__main__':
  64.     if len(sys.argv) == 2:
  65.         main()
  66.     else:
  67.         usage()

Reply to this snippet →

Top Languages

Python 2385
Text 73
Code 72
Haskell 36
Java 35
HTML 19
Bash 14
PHP 9
Diff 7
INI 5