Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用关键字在字典中搜索,python_Python_Python 2.7 - Fatal编程技术网

使用关键字在字典中搜索,python

使用关键字在字典中搜索,python,python,python-2.7,Python,Python 2.7,我有一个类似这样的函数,输入是一个包含一些关键字(字符串)的列表,并返回更适合字典中存储的所有关键字的关键字: def find_my_keyword(str1): dict_colour = { "y": {'has':["yellow", "white", "green"], 'hasnt':[]}, "z": {'has':["yellow", "white"], 'hasnt': ["green"]}, "z2": {'has':["yel

我有一个类似这样的函数,输入是一个包含一些关键字(字符串)的列表,并返回更适合字典中存储的所有关键字的关键字:

def find_my_keyword(str1):
   dict_colour = {
       "y": {'has':["yellow", "white", "green"], 'hasnt':[]},
       "z": {'has':["yellow", "white"], 'hasnt': ["green"]},
       "z2": {'has':["yellow", "white", "1."], '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


find_my_keyword(str1)
我尝试使用以下字符串:

str1 = ("white, "yellow", "1.2")
str2 = ("white, "yellow", "1.")
str3 = ("white, "yellow", "1.24")
函数仅使用str2返回颜色,它具有完全相同的项,是否有任何方法使函数在子字符串(1.)也位于字符串(1.2或1.24)中时返回颜色

我也试过这个,但效果不好:

for colour, keywords in dict_colour.items():
    if all(kw in keywords['has'] for kw in str1 ) and not any(kw in keywords['hasnt'] for kw in str1):
          return colour

我假设您想测试str1中的所有字符串是否都显示为
关键字['has']
中字符串的子字符串

在这种情况下,您可以使用:

for colour, keywords in dict_colour.items():
    if all(any(keystring in kw for keystring in keywords['has']) for kw in str1 ) and not any(kw in keywords['hasnt'] for kw in str1):
        return colour

这将考虑<代码> 1.2 /代码>和<代码> 1。< /代码>等。不变

def find_my_keyword(str1):
    dict_colour = {
        "y": {'has': ["yellow", "white", "green"], 'hasnt': []},
        "z": {'has': ["yellow", "white"], 'hasnt': ["green"]},
        "z2": {'has': ["yellow", "white", "1."], 'hasnt': ["green"]}}
    for colour, keywords in dict_colour.items():
        k_w = keywords["has"]
        if all(x in k_w or x.split(".")[0] + "." in k_w for x in str1):
            return colour
    return False
您只需检查
str1
中的所有单词是否都在
keywords[“has”]
中,如果它们都在
keywords[“hasnt”]


x.split(“.”[0]+“
1.24
更改为
1.
因此,当对照
1进行检查时,它返回
True

什么是“它需要一个字符串并返回更适合搜索的键”的意思?我不明白你的问题。我编辑了,我希望现在的问题更容易理解“不好的结果”-这是什么意思?!请提供您正在运行的代码的详细信息,并简要描述其问题。错误(提供完整的回溯)?意外输出(提供输入以及预期和实际输出)?