【问题标题】:Change all hex colors values to rgb将所有十六进制颜色值更改为 rgb
【发布时间】:2014-04-18 03:38:55
【问题描述】:

我有大约 50 个 css 文件,其中包含 200 多个颜色条目。我需要将所有十六进制颜色值转换为 rgb。有什么工具可以让我轻松完成任务,否则我必须打开每个 css 文件并手动完成。

例如

color:#ffffff;

应该转换成

color: rgb(255,255,255);

我对 Python 很满意,所以如果 Python 中有一些东西可以让我的工作更轻松。有很好的python method to do the hex to rgb conversion。但是我如何读取和替换 css 文件中的所有颜色值.. 确保它们将以 # 开头。

【问题讨论】:

  • 如果你使用 SASS,你可以通过计算将 hex 转换为 rgb。 stackoverflow.com/questions/9270844/…
  • @Sigma:但这仍然需要处理这 50 个文件才能将它们转换为使用 SASS,不是吗?
  • 投票重新开放;这不是一个要求我们推荐或查找工具、库或场外资源的问题。这是一个“给定 50 个文件,我将如何解决这个问题”的问题。
  • 这个问题似乎离题了,因为它不包括尝试的解决方案,为什么它们没有按照stackoverflow.com/help/on-topic中的说明工作
  • @martineau:见Should Stack Overflow be awarding "A"s for Effort?; OP 显然确实付出了一些努力来尝试弄清楚完成这项任务需要什么。

标签: python parsing python-2.7


【解决方案1】:

使用 fileinput module 创建一个可以处理 1 个或多个文件的脚本,并根据需要替换行。

使用正则表达式查找您的十六进制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

【讨论】:

  • @Martijin 对我来说看起来很棒,让我对我的文件进行测试,其中文件在单个文件中有多达 200 种不同的颜色条目
  • 错字:用 rbg 代替 rgb
  • 工作完美,但有两个更正它应该是“inplace=True”,正如@ddelemeny 指出的那样它应该是 rgb ..
  • @MartijnPieters 我发布了一个我正在使用的,也许你可以建议更优化的方式来 os.walk 或其他提示。
  • @DevC:我通常改用 UNIX 工具包;在灵活性和力量方面很难击败findfind somedir -name \*.css | xargs python scriptname.py 将为我们完成所有目录遍历,未来的选项将仅处理自给定日期以来更改的文件,或排除某些文件名或目录等。
【解决方案2】:

Martijin's 解决方案很棒。我不知道 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

【讨论】:

    【解决方案3】:

    对于想要更轻松控制并面临相同问题的人

    pip install pyopt-tools
    

    您可以使用Martijin's 正则表达式查找颜色并用此方法替换

    from pyopt_tools.colors import Color 
    
    c = Color("#ffffff")
    converted = c.to_rgb()
    print(converted)
    

    输出:

    (255, 255, 255)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2013-02-18
      • 2011-04-06
      • 1970-01-01
      相关资源
      最近更新 更多