Django“你的意思是?”询问

时间:2009-01-24 17:47:30

标签: python django spell-checking

我正在编写一个相当简单的Django应用程序,用户可以在其中输入字符串查询。应用程序将在数据库中搜索此字符串。

Entry.objects.filter(headline__contains=query)

这个查询非常紧张,但对于那些不能100%确定他们正在寻找什么的人来说并不是真的有用。所以我扩大了搜索范围。

from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)

我想为此添加一些额外的功能。搜索未拼写拼写单词,复数形式,常见同音异义词(声音拼写不同),等等。我只是想知道这些东西是否内置于Djangos查询语言中。对我来说写一个巨大的算法并不重要,因为我真的只是在寻找内置的东西。

提前感谢所有答案。

3 个答案:

答案 0 :(得分:11)

您可以尝试使用python的difflib模块。

>>> from difflib import get_close_matches
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']

问题是要使用difflib,必须从数据库中构建一个单词列表。这可能很昂贵。也许如果你缓存单词列表并且偶尔重建一次。

某些数据库系统支持搜索方法来执行您想要的操作,例如PostgreSQL的fuzzystrmatch模块。如果是这种情况,您可以尝试调用它。


修改

对于你的新“要求”,嗯,你运气不好。不,django的查询语言中没有内置任何内容。

答案 1 :(得分:5)

djangos orm没有开箱即用的这种行为,但有几个项目集成了django w / search服务,如:

我不能说选项#2和#3有多好用,但我已经使用了django-sphinx了很多,并对结果非常满意。

答案 2 :(得分:1)

cal_name = request.data['column']['name']

        words = []
        for col in Column.objects.all():
            if cal_name != col.name:
                words.append(col.name)
        words = difflib.get_close_matches(cal_name, words)
        if len(words) > 0 and is_sure != "true":
            return Response({
                'potential typo': 'Did you mean ' + str(words) + '?',
                "note": "If you think you do not have a typo send {'sure' : 'true'} with the data."})