Welcome, guest | Sign In | My Account | Store | Cart

Simple program that takes a CSS file and inverts all the colors,(e.g.: #ffffff -> #000000, #222 -> #ddd), then writes them to a file with the same name as the original plus "MOD".

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import re
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()

p6 = re.compile("#[0-9a-f]{6};", re.IGNORECASE)
p3 = re.compile("#[0-9a-f]{3};", re.IGNORECASE)
filepath = tkFileDialog.askopenfilename(title= "file?",)
content = file(filepath,'r').read()

def Modify (content):
    text = content.group().lower()
    code = {}
    l1="#;0123456789abcdef"
    l2="#;fedcba9876543210"
    for i in range(len(l1)):
        code[l1[i]]=l2[i]
    inverted = ""
    for j in text:
        inverted += code[j]
    return inverted

content = p6.sub(Modify,content)
content = p3.sub(Modify,content)

filepath = filepath[:-4]+"MOD.css"
out = file(filepath,'w')
out.write(content)
out.close()

This was actually a real-world requirement. The "Modify" function could easily be changed to add more red, darken, etc.

2 comments

greg p 16 years, 7 months ago  # | flag

Good Idea. This is a good idea. I thought it would be good to have it online, thus it's now a web utility:

http://www.utilitymill.com/utility/Invert_Hex_Colors

I simplified the code a bit too:

table = string.maketrans(
    '0123456789abcdef',
    'fedcba9876543210')

print hex_to_convert.lower().translate(table).upper()
rodrigo culagovski (author) 16 years, 5 months ago  # | flag
"I simplified the code a bit."

Nice use of understatement, there.