【问题标题】:Python dictionary vague key searchPython字典模糊键搜索
【发布时间】:2016-07-26 00:20:14
【问题描述】:

我想知道是否有办法在 python 字典中进行“模糊”键搜索。例如,我有一个这样的字典:

data = { "Google.com" : value1, "StackOverFlow": value2, ....}

如果我有一个字符串

name= "Google" or name = "google" or even name = "gooogle"

并且我想访问我的字典中的 value1(其键是“Google.com”),我该怎么做?我知道我可以遍历键列表并进行一些字符串处理,但是如果我有多个名称想要进行模糊搜索,那将是 O(n^2) 对吗?有没有有效的方法来做到这一点?假设数据字典非常非常大。

希望我的问题很清楚......

【问题讨论】:

标签: python dictionary search


【解决方案1】:

搜索时没有有效的模糊键。 Python 的 dict 使用散列来查找字典中的位置,对于相似的字符串,散列是完全不同的。让我们看看:

assert hash("Google.com") == 4399753695393964520
assert hash("Google.co") == -9213236188503134626

至少在我的操作系统中。

结论:你很少会通过使用相似的键获得“接近”所需的值。

所以:没有。使用 dicts 无法避免 O(n^2)。

【讨论】:

    【解决方案2】:

    如果您想进行一些模糊搜索,那么您实际上必须想出自己的散列算法。或者创建自己的字典变体,然后覆盖 .__getitem__ 和相关方法。

    这是一个例子:

    from jellyfish import soundex
    
    data = {soundex('google'): 'google.com', soundex('stackoverflow'): 'stackoverflow.com'}
    print(data[soundex('gooooogle')])
    # Should print `google.com`, because soundex pretty much ignores vowels
    

    或者替代方案:

    from jellyfish import soundex
    
    class SoundexDict(dict):
        # __init__ and __repr__ is left as an exercise for the reader
        def __getitem__(self, key):
            return super().__getitem__(soundex(key))
    
        def __setitem__(self, key, value):
            super().__setitem__(soundex(key), value)
    
    mydict = SoundexDict()
    mydict['google'] = 'google.com'
    print(mydict['gewgle'])  # prints 'google.com'
    

    【讨论】:

    • 用这样的语法填充数据字典似乎是非法的:data[soundex(name)]
    • 我的意思是,我收到 TypeError: expected unicode, got str
    • 您可能正在使用 Python2。您可能需要使用mydict[u'google'] = 'google.com',或调整设置器以执行soundex(key.encode()) 或其他操作。
    猜你喜欢
    • 2011-07-07
    • 1970-01-01
    • 2016-06-12
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多