将所有十六进制颜色值转换为RGB
我有大约50个CSS文件,里面有超过200个颜色的定义。我需要把所有的十六进制颜色值转换成RGB格式。有没有什么工具可以帮我轻松完成这个任务?要不我就得一个个打开CSS文件,手动去改。
比如说,
color:#ffffff;
应该转换成
color: rgb(255,255,255);
我对Python比较熟悉,所以如果有什么Python的工具可以让我工作更轻松就好了。其实有一个很好的Python方法可以进行十六进制到RGB的转换。但是我该怎么在CSS文件中读取和替换所有的颜色值呢?这些颜色值肯定都是以#开头的。
3 个回答
对于那些想要更简单控制并且遇到同样问题的人
pip install pyopt-tools
你可以使用Martijin的正则表达式来找到颜色,并用这种方法进行替换
from pyopt_tools.colors import Color
c = Color("#ffffff")
converted = c.to_rgb()
print(converted)
输出结果:
(255, 255, 255)
Martijin的解决方案非常棒。我之前不知道有fileinput这个模块,所以我每次都要读取每个文件,把替换后的内容放到临时文件里,然后再删除旧文件。但有了fileinput,这个过程变得简单又快了。下面是我的脚本,它需要一个文件夹作为参数,从当前目录开始遍历,找到所有的css文件并替换颜色。错误处理的部分还可以进一步改进。
import fileinput
import os
import sys
import re
_hex_colour = re.compile(r'#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b')
_current_path = os.getcwd() #folder arg should be from current working directory
_source_dir=os.path.join(_current_path,sys.argv[1]) #absolute path
cssfiles = []
def replace(match):
value = match.group(1)
if len(value) == 3: # short group
value = [str(int(c + c, 16)) for c in value]
else:
value = [str(int(c1 + c2, 16)) for c1, c2 in zip(value[::2], value[1::2])]
return 'rgb({})'.format(', '.join(value))
for dirpath, dirnames, filenames in os.walk (_source_dir):
for file in filenames:
if file.endswith(".css"):
cssfiles.append(os.path.join(dirpath,file))
try:
for line in fileinput.input(cssfiles,inplace=True):
line = _hex_colour.sub(replace, line)
sys.stdout.write(line)
print '%s files have been changed'%(len(cssfiles))
except Exception, e:
print "Error: %s"%(e) #if something goes wrong
使用 fileinput
模块 来创建一个脚本,这个脚本可以处理一个或多个文件,并根据需要替换其中的行。
使用正则表达式来找到你的十六进制 RGB 值,并注意有两种格式;#fff
和 #ffffff
。你需要替换这两种格式:
import fileinput
import sys
import re
_hex_colour = re.compile(r'#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b')
def replace(match):
value = match.group(1)
if len(value) == 3: # short group
value = [str(int(c + c, 16)) for c in value]
else:
value = [str(int(c1 + c2, 16)) for c1, c2 in zip(value[::2], value[1::2])]
return 'rgb({})'.format(', '.join(value))
for line in fileinput.input(inplace=True):
line = _hex_colour.sub(replace, line)
sys.stdout.write(line)
这个正则表达式会寻找一个 #
符号,后面跟着 3 或 6 个十六进制数字,再后面是一个单词边界(意思是后面不能跟字符、数字或下划线);这样可以确保我们不会意外匹配到更长的十六进制值。
对于 #hhh
(3 位数字)的格式,会通过将每个十六进制数字重复一遍来转换;比如 #abc
相当于 #aabbcc
。这些十六进制数字会被转换成整数,然后再转成字符串,方便格式化,最后放入一个 rgb()
字符串中,准备进行替换。
fileinput
模块会从命令行获取文件名;如果你把这个保存为一个 Python 脚本,那么:
python scriptname.py filename1 filename2
就会同时转换这两个文件。如果没有提供文件名,则会使用 stdin
。