使用关键字查找项目



我想问这个问题。多年来,我一直在尝试编写一个可以有效地做到这一点的程序,但很难到达任何地方。本质上,我有一个字符串存储在字典中,如下所示:

dic = {"a" : "Blue Jacket with buttons", "b" : "Green Jacket with a buttons",
      "c" : "Blue jacket"}

假设我想找到"b",但用户不知道它在字典中的确切存储方式,因此他们输入了他们希望用来查找该项目的关键字。

keywords = "Blue, Jacket, Buttons"
keywords.split(",")

我将如何使用关键字在字典中找到"b"?我尝试做一个 if 语句,但我无法让它注意到"a"和"c"之间的区别。如何使用关键字查找字典中的项目?

谢谢!

这是我

的尝试,使用set函数。只有当所有关键字都可以在相应的值中找到时,我们才会选择键。

keywords = set([x.strip() for x in "Blue, Jacket, Buttons".lower().split(",")])
print([key for key, val in dic.items() if keywords <= set(val.lower().split())])

我以下面的代码为例。在这里,我查找所有值中具有"蓝色"的键。无论如何,正如COLDSPEED所说,字典的这种使用是非常未经优化的。

dic = {"a" : "Blue Jacket with buttons", "b" : "Green Jacket with a buttons",
  "c" : "Blue jacket"}
keywords = "Blue, Jacket, Buttons"
keywords = keywords.split(",")
for key, value in dic.iteritems():
    if keywords[0] in value:
        print key

代码如下:

def main():
    dic = {"a": "Blue Jacket with buttons", "b": "Green Jacket with a buttons",
           "c": "Blue jacket"}
    keywords = "Blue, Jacket, Buttons"
    keyword_items = [keyword.strip().lower() for keyword in keywords.split(",")]
    for key, value in dic.items():
        if all(keyword in value.lower() for keyword in keyword_items):
            print(key)

你可以尝试使用difflib:

>>> import difflib
>>> dic = {"a" : "Blue Jacket with buttons", "b" : "Green Jacket with a buttons","c" : "Blue jacket"}
>>> keywords = "Blue, Jacket, Buttons"
>>> result = max((difflib.SequenceMatcher(a=keywords.lower(), b=value.lower()).ratio(),key) for key, value in dic.items())
>>> result
(0.8444444444444444, 'a')
>>> result[1]
'a'

最新更新