DJango如何实现分词搜索?

这种分词搜索是如何实现的,这是微信开放社区的页面,例如我搜索“PPT模板文件”,系统会自动拆分为:PPT文件,PPT,PPT模板,文件,模板

image.png

这种功能如何实现呢?

阅读 869
avatarAI BotBETA

要实现分词搜索,你可以使用Django中的whoosh库。whoosh是一个Python库,它提供了一个简单的搜索界面,支持全文搜索和布尔查询等功能。

首先,你需要安装whoosh库。你可以使用以下命令在Django项目中安装它:

pip install whoosh

接下来,你需要创建一个搜索引擎索引。在Django中,你可以使用whoosh库的WhooshIndexer类来创建一个索引。你需要将你的模型类与索引器类关联起来,并定义哪些字段需要被索引。

以下是一个示例:

from django.db import models
from whoosh.index import Index, NoSuchIndexError
from whoosh.fields import Schema, ID, TEXT, BOOLEAN
from whoosh.qparser import MultifieldParser

class Product(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    # 其他字段...

    class Meta:
        app_label = 'myapp'  # 指定应用的名称,确保它与你在settings.py文件中定义的'SEARCH_APPS'匹配

class ProductIndex(Index):
    def __init__(self, using=None):
        self.schema = Schema(id=ID(unique=True), title=TEXT(boost=5), description=TEXT, price=TEXT, keywords=TEXT)
        super(ProductIndex, self).__init__(using=using)

    def index_queryset(self, using=None):
        return Product.objects.all()

在上面的示例中,我们创建了一个名为Product的模型,并定义了几个字段。然后,我们创建了一个名为ProductIndex的索引器类,它将模型中的字段映射到相应的字段类型。在这个例子中,我们使用了TEXT类型来索引标题、描述、价格和关键字字段。我们还将标题字段的权重设置为5,以便在搜索时给予更高的权重。

接下来,你需要在Django项目的设置文件中配置whoosh搜索引擎。打开你的设置文件并添加以下配置:

SEARCH_APPS = [    ('myapp', r'myapp\.ProductIndex'),    ]

确保将myapp替换为你的应用名称,并将ProductIndex替换为你的索引器类的名称。这将告诉whoosh在哪里查找索引和如何解析查询。

最后,你可以在你的视图或模板中使用whoosh来执行分词搜索。以下是一个示例视图函数:

from django.shortcuts import render, render_to_response
from whoosh.query import And, Or, Term, Prefix
from whoosh.fields import ID, TEXT, BOOLEAN
from whoosh.index import open_dir
from myapp.models import Product, ProductIndex
from myapp.forms import ProductSearchForm
import whoosh.indexer as ixwriter
import whoosh.query as queryparser
import whoosh.fields as fieldtypes
import whoosh.highlight as highlighters
import re
1 个回答

django 是 python 的库,你怎么打上了 java 的标签。

pip install jieba
import jieba

s = 'PPT模板文件'

jieba.lcut(s, cut_all=True) # ['PPT', '模板', '文件']

jieba.lcut_for_search(s) # ['PPT', '模板', '文件']

分完词后你可以对文本进行匹配,将分好的词在文本中标记高亮,就可以变成图中的形式。

jieba 地址:https://github.com/fxsjy/jieba

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题