gpt4 book ai didi

python - 在python3中将hsl转换为十六进制

转载 作者:行者123 更新时间:2023-12-05 01:19:08 24 4
gpt4 key购买 nike

我从 atom one-dark syntax 中获取了以下字符串:

one_dark_syn = """
@hue-1: hsl(187, 47%, 55%); // <-cyan
@hue-2: hsl(207, 82%, 66%); // <-blue
@hue-3: hsl(286, 60%, 67%); // <-purple
@hue-4: hsl( 95, 38%, 62%); // <-green
@hue-5: hsl(355, 65%, 65%); // <-red 1
@hue-5-2: hsl( 5, 48%, 51%); // <-red 2
@hue-6: hsl( 29, 54%, 61%); // <-orange 1
@hue-6-2: hsl( 39, 67%, 69%); // <-orange 2
"""

我想使用 python 将 hsl 值交换为十六进制。到目前为止,我编造了一组看起来很讨厌的循环来将值解析成一个 numpy 数组:

od_colors = [i.split(";")[0].split(":")[1] for i in one_dark_syn.split("\n") if "hsl" in i]
od_colors = [i.strip().replace("%","").replace("hsl","").replace(" ","") for i in od_colors]
od_colors = [i.replace("(","").replace(")","").split(",") for i in od_colors]
od_colors = np.array(od_colors,dtype="int32")

就像我说的那样令人讨厌。有没有人有更pythonic的方式来解析这个?最重要的是,您建议我如何将 hsl 转换为十六进制?

最佳答案

我会使用正则表达式:

regex = r'hsl\(\s*(\d+),\s*(\d+)%,\s*(\d+)%\s*\);'
lines = [re.findall(regex,line) for line in one_dark_syn.split('\n')]
rgbs = [colorsys.hsv_to_rgb(int(line[0][0])/360,
int(line[0][1])/100,
int(line[0][2])/100) for line in lines if line]
# [(0.2915, 0.519842, 0.55), (0.1188, 0.41646, 0.66), (0.5762, 0.268, 0.67),
# (0.48257, 0.62, 0.3844), (0.65, 0.2275, 0.2627), (0.51, 0.2856, 0.2652),
# (0.61, 0.43981, 0.2806), (0.69, 0.528195, 0.2277)]

最后,将 RGB 三元组转换为 HEX 字符串:

rgbhex = ["".join("%02X" % round(i*255) for i in rgb) for rgb in rgbs]
# ['1D3437', '0C2A42', '3A1B43', '303E26', '41171A', '331D1B', '3D2C1C', '453517']

关于python - 在python3中将hsl转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com