iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0

昨天成功給題目加上標籤作為分類依據,今天讓加上的標籤可以做為搜尋條件。

▍程式碼

  1. 先給前端加上下拉選單
<!-- index.html -->

<form method="GET" action="/search">
    <div class="input-group">
        <!-- searchtype用來分辨現在是什麼搜尋 -->
        <input type="hidden" name="searchtype" value="tag">
        <select class="form-select" name="tag" aria-label="搜尋">
            <option selected disabled>請選擇標籤搜尋...</option>
            {% for tag in all_tags %}
            <option value={{ tag }}>{{ tag }}</option>
            {% endfor %}
        </select>
    </div>
    <div class="input-group-append">
        <button type="submit" class="btn btn-primary">標籤搜尋</button>
    </div>
</form>
  1. 把關鍵字搜尋和標籤搜尋區分開
# views.py

@app.route('/search')
def search():
    search_type = request.args.get('searchtype')
    query = request.args.get(search_type, '').lower()
    match = False

    if query:
        search_results = []
        result_word = "查詢結果"
        for item in KNOWLEDGE_BASE:
            # 如果是關鍵字搜尋就查找題目和答案
            if ( search_type == 'q' and ( ... ):
                match = True
                
            # 如果是標籤搜尋,查找標籤
            elif search_type == 'tag' :
                for tag in item["標籤"]:
                    if (query in tag.lower()) :
                        match = True

            # 如果有找到對應題目,把題目資訊加入列表
            if match :
                search_results.append({
                    "question_text": item.get("題目", ""),
                    "options": item.get("選項", []),
                    "book_source": item.get("來源書籍", ""),
                    "page_number": item.get("頁次", ""),
                    "source_filename": item.get("來源檔案", ""),
                    "answer": item.get("答案", "")
                })
        ...
    return render_template(
        ...
    )
  1. 讀取所有標籤加入下拉選單
# views.py

def get_tag():
    # 提取、去重所有標籤
    all_tags = set()
    for item in KNOWLEDGE_BASE:
        if '標籤' in item and isinstance(item['標籤'], list):
            for tag in item['標籤']:
                all_tags.add(tag)

    return sorted(list(all_tags))

@app.route('/')
@app.route('/home')
def home():
    tags=get_tag()
    return render_template(
        ...
        all_tags=tags
    )

最後搜尋一下測試,這裡選擇"電子病歷"標籤。
https://ithelp.ithome.com.tw/upload/images/20250921/20169370UYyxPj98lv.png
https://ithelp.ithome.com.tw/upload/images/20250921/20169370ZWVkAiBU1u.png


上一篇
DAY6 - AI標籤生成
下一篇
DAY8 - 進階搜尋
系列文
打造你的數位圖書館:從雜亂檔案到個人化知識庫9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言