Skip to content

Instantly share code, notes, and snippets.

@christopherkullenberg
Created August 29, 2016 19:53
Show Gist options
  • Save christopherkullenberg/11ddf0425306baa0a83f02301627d396 to your computer and use it in GitHub Desktop.
Save christopherkullenberg/11ddf0425306baa0a83f02301627d396 to your computer and use it in GitHub Desktop.
'''Use with Python3'''
import re
import struct
import textwrap
thefile = open('style.css', encoding="utf-8")
lines = thefile.readlines()
def colorchanger(hexnumber):
'''Substitute hex colors according to Andrejs formula. Return RGB-strings for CSS'''
if len(hexnumber) == 3:
#print("three")
sixdigit = colorre[0] + colorre[0]
#print(sixdigit)
hexadec = struct.unpack('BBB',bytes.fromhex(sixdigit))
#print(hexadec[0], hexadec[1], hexadec[2])
sumhex = hexadec[0] + hexadec[1] + hexadec[2]
yy = round(256 - (sumhex / 3))
#print(yy)
result = str(yy) * 3
#print("Result: " + result)
if len(result) == 3:
tripletlist = textwrap.wrap(result, 1)
elif len(result) == 6:
tripletlist = textwrap.wrap(result, 2)
elif len(result) == 9:
tripletlist = textwrap.wrap(result, 3)
#print(tripletlist)
rgb = "rgb(" + tripletlist[0] + ", " + tripletlist[1] + ", " + tripletlist[2] + ")"
if len(hexnumber) == 6:
#print("six")
#print("original" + hexnumber)
hexadec = struct.unpack('BBB',bytes.fromhex(hexnumber))
#print(hexadec[0], hexadec[1], hexadec[2])
sumhex = hexadec[0] + hexadec[1] + hexadec[2]
yy = round(256 - (sumhex / 3))
#print("yy" + str(yy))
result = str(yy) * 3
if len(result) == 3:
tripletlist = textwrap.wrap(result, 1)
elif len(result) == 6:
tripletlist = textwrap.wrap(result, 2)
elif len(result) == 9:
tripletlist = textwrap.wrap(result, 3)
rgb = "rgb(" + tripletlist[0] + ", " + tripletlist[1] + ", " + tripletlist[2] + ")"
return(rgb)
# Substitute old colors with new ones then write a new file
newfile = open('newstyle.css', "w")
for l in lines:
colorre = re.findall(r'color\:\s\#(.*)(?=\;)', l)
if not colorre:
print(l)
newfile.write(l)
elif colorre:
newstring = l.replace(colorre[0], colorchanger(colorre[0]))
newstringminushash = newstring.replace("#", "")
print(newstringminushash)
newfile.write(newstringminushash)
newfile.close()
print("Wrote new file newfile.css. Have a nice day!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment