【问题标题】:Django "Did you mean?" query姜戈:“你的意思是?”询问
【发布时间】:2010-10-03 08:20:17
【问题描述】:

我正在编写一个相当简单的 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)

我想为此添加一些额外的功能。搜索未拼写的单词、复数、常见的同音字(发音相同,拼写不同)等。我只是想知道这些东西是否内置在 Django 查询语言中。编写一个庞大的算法对我来说还不够重要,因为我真的只是在寻找内置的东西。

提前感谢所有答案。

【问题讨论】:

  • 您正在寻找“Soundex”搜索算法:en.wikipedia.org/wiki/Soundex
  • Eh ... Soundex 最初旨在捕捉英文姓氏的笔误。对于一般词汇,它的用处不大。

标签: python django spell-checking


【解决方案1】:

您可以尝试使用 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 的查询语言中没有内置任何内容。

【讨论】:

    【解决方案2】:

    djangos orm 没有这种开箱即用的行为,但是有几个项目将 django 与搜索服务集成在一起,例如:

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

    【讨论】:

      【解决方案3】:
      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."})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-16
        • 2022-07-21
        • 2020-08-17
        • 2013-02-22
        • 1970-01-01
        • 2020-12-10
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多