我正在寻找一种检查字符串是否定义颜色的方法,因为我的程序依赖于用户输入颜色而当它们输入错误颜色时会中断。我怎样才能做到这一点?以下是一些例子:
check_color("blue") > True
check_color("deep sky blue") > True
check_color("test") > False
check_color("#708090") > True
答案 0 :(得分:2)
一种可能的方法是使用colour
包。如果您没有安装,请使用命令pip install colour
。然后,您可以使用以下内容:
from colour import Color
def check_color(color):
try:
# Converting 'deep sky blue' to 'deepskyblue'
color = color.replace(" ", "")
Color(color)
# if everything goes fine then return True
return True
except ValueError: # The color code was not found
return False
check_color("blue")
check_color("deep sky blue")
check_color("test")
check_color("#708090")
答案 1 :(得分:1)
这是使用matplotlib检查字符串是否定义颜色的方法:
>>> from matplotlib.colors import is_color_like
>>>
>>> is_color_like('red')
True
>>> is_color_like('re')
False
>>> is_color_like(0.5)
False
>>> is_color_like('0.5')
True
>>> is_color_like(None)
False
>>>
>>> matplotlib.colors.__file__
'/usr/lib/python2.7/site-packages/matplotlib/colors.py'
在matplotlib.colors模块的源代码中编写为:
该模块还提供用于检查对象是否可以被识别的功能。 解释为颜色(:func:
is_color_like
),用于转换此类对象 到RGBA元组(:func:to_rgba
)或HTML格式的十六进制字符串中#rrggbb
格式(:func:to_hex
),以及(n, 4)
的一系列颜色 RGBA数组(:func:to_rgba_array
)。缓存用于提高效率。
答案 2 :(得分:0)
你应该使用这样的东西:
import re
VALID_COLORS = ['blue', 'red']
HEX_COLOR_REGEX = r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$'
def is_hex_color(input_string):
regexp = re.compile(HEX_COLOR_REGEX)
if regexp.search(input_string):
return True
return False
def is_color(input_string):
for color in VALID_COLORS:
if color in input_string or is_hex_color(input_string):
return True
return False
答案 3 :(得分:0)
您可以使用外部颜色模块。使用pip安装颜色模块:
pip install colour
然后你可以这样做:
>>> from colour import Color
>>> name = "blue"
>>> try:
Color(name.replace(" ",""))
print("Valid Color")
except:
print("Invalid color")
因为在找不到颜色时会引发异常。
答案 4 :(得分:0)
在tkinter中:widget.winfo_rgb('color')