昨天成功給題目加上標籤作為分類依據,今天讓加上的標籤可以做為搜尋條件。
<!-- 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>
# 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(
...
)
# 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
)
最後搜尋一下測試,這裡選擇"電子病歷"標籤。