最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于python + django + whoosh + jieba 分詞器實(shí)現(xiàn)站內(nèi)檢索功能

 更新時(shí)間:2021年08月25日 15:37:50   作者:一肚子頂死你  
這篇文章主要介紹了基于python + django + whoosh + jieba 分詞器實(shí)現(xiàn)站內(nèi)檢索功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

基于 python django

源碼

前期準(zhǔn)備

安裝庫:

pip install django-haystack
pip install whoosh
pip install jieba

如果pip 安裝超時(shí),可配置pip國(guó)內(nèi)源下載,如下:

pip install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com   <安裝的庫>
pip install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com  django

如果安裝 django-haystack 失敗,先安裝 setuptools_scm .在安裝 django-haystack.

pip install setuptools_scm

項(xiàng)目

 創(chuàng)建項(xiàng)目demo:

# django-admin startproject <項(xiàng)目名>
	django-admin startproject find

切入demo 終端操作,創(chuàng)建app:

# python manage.py startapp <APP名>
	python manage.py startapp searchshop

在 settings.py 文件 中的 INSTALLED_APPS 配置 注入 剛才創(chuàng)建APP( 路徑: find/find/settings.py):

INSTALLED_APPS = [
	...
	'searchshop',
	...
]

在創(chuàng)建的APP中添加模型

models.py 文件添加如下(路徑: find/searchshop/models.py):

class Shopp(models.Model):
    shop_name = models.TextField(max_length=200)
    shop_price = models.IntegerField(default=0)
    shop_dsc = models.CharField(max_length=200)

在app 中admin.py文件注冊(cè)模型:

admin.py 文件添加如下(路徑: find/searchshop/admin.py):

from .models import Shopp
admin.site.register(Shopp)

執(zhí)行命令,讓模型生效(修改模型時(shí),都要執(zhí)行一次,這樣模型才同步!!!):

python manage.py makemigrations 
python manage.py migrate

創(chuàng)建后臺(tái)管理帳號(hào)

訪問后臺(tái)可操作模型數(shù)據(jù):

 python manage.py createsuperuser

運(yùn)行:

python manage.py runserver

訪問: http:127.0.0.1:8080/admin 登錄剛才設(shè)置帳號(hào),密碼即可進(jìn)入:

在這里插入圖片描述

搭建站內(nèi)搜索

配置 haystack

在 settings.py 文件 中的 INSTALLED_APPS 配置最底部 注入 haystack( 路徑: find/find/settings.py):

INSTALLED_APPS = [
	...
	'haystack'
]

在app內(nèi),添加 search_indexes.py (目錄:find/searchshop/search_indexes.py):

from haystack import indexes
from .models import Shopp # 之前創(chuàng)建的模型

# 修改此處,類名為模型類的名稱+Index,比如模型類為GoodsInfo,則這里類名為GoodsInfoIndex(其實(shí)可以隨便寫)
class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable):
    # text為索引字段
    # document = True,這代表haystack和搜索引擎將使用此字段的內(nèi)容作為索引進(jìn)行檢索
    # use_template=True 指定根據(jù)表中的那些字段建立索引文件的說明放在一個(gè)文件中
    text = indexes.CharField(document=True, use_template=True)

    # 對(duì)那張表進(jìn)行查詢
    def get_model(self):  # 重載get_model方法,必須要有!
        # 返回這個(gè)model
        return Shopp

    # 建立索引的數(shù)據(jù)
    def index_queryset(self, using=None):
        # 這個(gè)方法返回什么內(nèi)容,最終就會(huì)對(duì)那些方法建立索引,這里是對(duì)所有字段建立索引
        return self.get_model().objects.all()

生成檢索索引

python manage.py rebuild_index

項(xiàng)目目錄多出whoosh_index文件夾.

修改分詞器

從 pyrhon 安裝路徑 ( \Lib\site-packages\haystack\backends\whoosh_backend.py) 復(fù)制一份到app中改名為 whoosh_cn_backend (find/searchshop/whoosh_cn_backend.py)
在頂部引用:

from jieba.analyse import ChineseAnalyzer

找到 (查找 StemmingAnalyzer ) 位置:

 schema_fields[field_class.index_fieldname] = TEXT(
                    stored=True,
                    analyzer=StemmingAnalyzer(),
                    field_boost=field_class.boost,
                    sortable=True,
                )

替換:

schema_fields[field_class.index_fieldname] = TEXT(stored=True, analyzer=ChineseAnalyzer(),
                    field_boost=field_class.boost)

在 INSTALLED_APPS(路徑: find/find/settings.py) 配置后面 后面添加:

HAYSTACK_CONNECTIONS = {
    'default': {
        # 指定whoosh引擎 (之前創(chuàng)建的whoosh_cn_backend)
        'ENGINE': 'searchshop.whoosh_cn_backend.WhooshEngine',
        # 'ENGINE': 'jsapp.whoosh_cn_backend.WhooshEngine',      # whoosh_cn_backend是haystack的whoosh_backend.py改名的文件為了使用jieba分詞
        # 索引文件路徑
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}
 # 添加此項(xiàng),當(dāng)數(shù)據(jù)庫改變時(shí),會(huì)自動(dòng)更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

添加 templates

在APP中創(chuàng)建 templates文件夾.

添加內(nèi)容檢索內(nèi)容

在templates文件夾下創(chuàng)建文件夾 search -> indexes -> searchshop( search + APP名);
路徑( 目錄: find/searchshop\templates\search\indexes\searchshop) 添加Shopp_text.txt(APP名_text.txt): (需要檢索的字段名)

{{object.shop_name}}
{{object.shop_dsc}}
{{object.shop_price}}

添加頁面模板

在templates文件夾下創(chuàng)建文件夾(searchshop) 下創(chuàng)建index.html:

{% load highlight %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <style>
        span.highlighted {
            color: red;
        }
    </style>
</head>
<body>
    <div class="search">
        <form method="get" action="{% url 'shop:search' %}">
            <input type="text" name="q" placeholder="a搜索商品">
            <input type="submit" value="搜索">
        </form>
    </div>
    {% if shop_list and query %}
    <ul>
        {% for question in shop_list %}
        <li>
            {% highlight question.object.shop_name with query %}
            價(jià)格: {% highlight question.object.shop_price with query %}
            <span class="post-author"> <a> {% highlight question.object.shop_dsc with query %} </a></span>
        </li>
        {% endfor %}
    </ul>
    {% else %}
    <p>No polls are available.</p>
    {% endif %}
</body>
</html>

load highlight : 加載高亮.
query : 檢索詞
shop_list : 檢索結(jié)果

視圖層

目錄: find/searchshop/views.py

from django.shortcuts import render
from django.http import HttpResponse
#Create your views here.
from .models import Shopp
from haystack.forms import  ModelSearchForm
from haystack.query import EmptySearchQuerySet
def index(request):
   shop_list = Shopp.objects.all()
   context = {
       'query': '',
       'shop_list': shop_list
   }
   return render(request, 'searchshop/index.html', context)

def search(request,  load_all=True, form_class=ModelSearchForm, searchqueryset=None):
   if request.GET.get('q'):
       form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)

       if form.is_valid():
           query = form.cleaned_data['q']
           results = form.search()
           context = {
               'query': query,
               'shop_list': results
           }
           return render(request, 'searchshop/index.html', context)
           # results = form.search()
       return HttpResponse(request.GET.get('q'))
   return HttpResponse('查詢')

配置路由

在 find/searchshop 創(chuàng)建 urls.py

from . import views
app_name = 'shop'   # 重點(diǎn)是這一行
urlpatterns = [
   path('', views.index, name='index'),
   path('search', views.search, name='search'),
   #  path(r'search/$', views.search, name='search')
]

修改 urls.py(目錄: find/find/urls.py)

from django.urls import path, include

urlpatterns = [
   path('shop', include('searchshop.urls')),
   path('admin/', admin.site.urls),
]

運(yùn)行:

python manage.py runserver

測(cè)試

http://127.0.0.1:8000/shop

在這里插入圖片描述
在這里插入圖片描述

分詞器

所以'紅米'查詢不到…

在這里插入圖片描述

到此這篇關(guān)于基于python + django + whoosh + jieba 分詞器實(shí)現(xiàn)站內(nèi)檢索的文章就介紹到這了,更多相關(guān)python django 分詞器實(shí)現(xiàn)站內(nèi)檢索內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 玩轉(zhuǎn)Python圖像處理之二值圖像腐蝕詳解

    玩轉(zhuǎn)Python圖像處理之二值圖像腐蝕詳解

    這篇文章主要給大家介紹了關(guān)于Python圖像處理之二值圖像腐蝕的相關(guān)資料,對(duì)原圖進(jìn)行二值化后,選擇不同的結(jié)構(gòu)元素對(duì)其進(jìn)行膨脹和腐蝕運(yùn)算處理,并仿真出圖像結(jié)果,需要的朋友可以參考下
    2021-09-09
  • Python DataFrame Rank詳解

    Python DataFrame Rank詳解

    在數(shù)據(jù)分析中,pandas庫的DataFrame對(duì)象的rank()方法可用于計(jì)算數(shù)據(jù)排名,處理重復(fù)值并支持多種參數(shù)定制排名規(guī)則,如ascending、axis、numeric_only等,是數(shù)據(jù)分析和競(jìng)賽中的有力工具
    2024-09-09
  • python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹

    python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹

    這篇文章主要介紹了python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹,具有很好參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié)

    python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié)

    數(shù)據(jù)類型轉(zhuǎn)換是常見的功能,本文主要介紹了python中l(wèi)ist,ndarray,Tensor間的轉(zhuǎn)換小結(jié),文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • python實(shí)現(xiàn)簡(jiǎn)單加密解密機(jī)制

    python實(shí)現(xiàn)簡(jiǎn)單加密解密機(jī)制

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單加密解密機(jī)制,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • Python使用Nocalhost并開啟debug調(diào)試的方法

    Python使用Nocalhost并開啟debug調(diào)試的方法

    Nocalhost是一種開發(fā)者工具,支持針對(duì)Kubernetes應(yīng)用程序進(jìn)行調(diào)試和部署,這篇文章主要介紹了Python怎么使用Nocalhost并開啟debug,需要的朋友可以參考下
    2023-04-04
  • 實(shí)例講解Python設(shè)計(jì)模式編程之工廠方法模式的使用

    實(shí)例講解Python設(shè)計(jì)模式編程之工廠方法模式的使用

    這篇文章主要介紹了Python設(shè)計(jì)模式編程之工廠方法模式的運(yùn)用實(shí)例,文中也對(duì)Factory Method模式中涉及到的角色作出了解析,需要的朋友可以參考下
    2016-03-03
  • python3安裝speech語音模塊的方法

    python3安裝speech語音模塊的方法

    今天小編就為大家分享一篇python3安裝speech語音模塊的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python如何在ubuntu中更改Python和pip指向

    Python如何在ubuntu中更改Python和pip指向

    這篇文章主要介紹了Python如何在ubuntu中更改Python和pip指向問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Python 位置參數(shù)基礎(chǔ)教程示例

    Python 位置參數(shù)基礎(chǔ)教程示例

    這篇文章主要為大家介紹了Python 位置參數(shù)基礎(chǔ)教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09

最新評(píng)論

海兴县| 富蕴县| 墨江| 监利县| 麻江县| 苏尼特右旗| 元氏县| 若羌县| 汉沽区| 威远县| 巧家县| 弥渡县| 甘孜县| 潮州市| 富顺县| 仁化县| 广灵县| 凌海市| 柞水县| 城口县| 华坪县| 四川省| 定南县| 怀仁县| 南溪县| 柳林县| 神木县| 确山县| 甘德县| 乡城县| 城步| 肇庆市| 绥阳县| 张家口市| 彭州市| 调兵山市| 广州市| 肥东县| 涿州市| 桃源县| 栾城县|