我有一个字典和一个字符串,还有一个我希望返回“y”的函数,但现在可以返回“y”或“z”:
import re
def find_my_keyword():
dict_colour = {
"x": ["back", "blue", "green"],
"y": ["yellow", "white", "green"],
"z": ["yellow", "white"]
}
str1 = "I have yellow, green and white"
for colour, keywords in dict_colour.items():
if all(re.search(kw, str1) for kw in keywords):
return colour
有没有办法在我的z列表中添加新数组,而不是绿色:
"z": ["yellow", "white", =! "green"] ?
或者是任何库在python中完成这个功能吗?
答案 0 :(得分:2)
不,你不能改变python语法。但是可以得到理想的结果。只需采用惯例,例如not在关键字的开头由~
表示。然后你可以这样做:
def find_my_keyword():
dict_colour = {
'x': ['black', 'blue', 'green'],
...
'z': ['yellow', 'white', '~green']
}
str1 = 'I have yellow, green, white'
for key in dict_colour:
if all(colour not in str1 if colour.startswith('~') else colour in str1 for colour in dict_colour[key]):
return key
答案 1 :(得分:2)
没有。我建议这样的事情:
...
"y": {'has':["yellow", "white", "green"], 'hasnt':[]}
"z": {'has':["yellow", "white"], 'hasnt': ["green"]}
...
for colour, keywords in dict_colour.items():
if all(kw in str1 for kw in keywords['has']) and not any(kw in str1 for kw in keywords['hasnt']):
return colour
答案 2 :(得分:0)
有一些方法可以创建不应包含特定单词的正则表达式模式。 This answer可能是您正在寻找的。 尝试用
替换dict_colour
dict_colour = {
"x": ["back", "blue", "/^((?!green).)*$/"],
"y": ["yellow", "white", "/^((?!green).)*$/"],
"z": ["yellow", "white"]
}