Python 程式如何找出與問題最相似的句子?

林邦源 · AI 筆記 · 2026年11月3日 · 閱讀時間約 7 分鐘

English 繁體中文 简体中文

一位顧客輸入「What is your address?」。普通的關鍵字搜尋只會找到 包含這些字眼的行。但一個小型 AI 模型可以拿問題的意思,與檔案中的 每一句比較,並選出最接近的一句——即使措辭不同。

本文的程式正是為一間小餐廳做這件事:它讀取一個載有餐廳資料的純文字檔, 找出與問題最相似的句子並印出來,全程只用 20 行。無需帳戶、無需金鑰、 無需費用——一切在你自己的電腦上執行。

資料檔案

餐廳的知識是一個純文字檔 sentences-restaurant.txt,每行一項資料:

Opening hour 9am-11pm
Address : Unit 10, 2F, Festival Walk, Kowloon Tong
Set lunches beef set $100, Pork set $110, Chicken set $120

這個檔案已包含在示範 zip 內,所以你可以先執行程式,之後才修改句子。

一分鐘看懂原理

背後靠兩件數學工具。第一,一個預先訓練好的模型把每句句子變成一列數字,稱為 嵌入向量(embedding):把這些數字想像成座標,每句句子就變成一個點, 而意思相近的句子最終會靠在一起。第二,餘弦相似度(cosine similarity)比較兩列這樣的數字,方法是量度它們之間的夾角。 得分為 1 代表方向相同、意思相同;0 代表毫不相關。程式選出得分最高的 句子——而且只在得分夠好時才作答。這種按意思尋找文字、不靠生成式模型憑空寫作的方法, 正是我的工作論文的主題:Lam, Pong Yuen (2026), “Natural Language Processing: Foundations and Applications without Hallucination from Generative AI”, Working Paper. Available at SSRN: https://doi.org/10.2139/ssrn.7384558。 亦可參閱我的研究頁面。

逐段拆解程式

from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer('BAAI/bge-m3')

這裡引入了兩個函式庫。SentenceTransformer 載入一個現成的模型, 把句子變成嵌入向量;BAAI/bge-m3 是由北京智源人工智能研究院(Beijing Academy of Artificial Intelligence)訓練的模型,能妥善處理多種語言, 所以我們無需自行訓練任何東西——模型網頁見 huggingface.co/BAAI/bge-m3。 首次執行會下載約 2 GB,所以需要互聯網一次; 之後模型已儲存在電腦上。numpy——習慣上簡寫為 np—— 是快速數列運算的標準函式庫。

with open('sentences-restaurant.txt', 'r', encoding='utf-8') as f:
    sentences = [line.strip() for line in f.readlines() if line.strip()]

user_question = "What is your address?"

檔案被讀入一個句子清單,每行前後的空白會被移除,空行會被略過。問題獨佔一行, 所以很容易改動它來問其他問題。

question_embedding = model.encode(user_question.strip().lower())
sentence_embeddings = model.encode([s.lower() for s in sentences])

model.encode 把文字變成嵌入向量:先是問題,然後是檔案中的每一句。 一切都先轉成小寫,令大寫字母不影響比較。嵌入向量也稱為向量(vector) ——一支由數字組成、指向句子意思的箭頭。

dot_product = np.dot(sentence_embeddings, question_embedding)
dense_scores = dot_product / (np.linalg.norm(sentence_embeddings, axis=1) * np.linalg.norm(question_embedding))

點積(dot product,np.dot) 把兩個向量相乘;把它除以兩條長度(np.linalg.norm——norm 即長度),便得出兩者夾角的餘弦。結果 dense_scores 是每句句子一個 得分:問題分別與第 1 行、第 2 行、第 3 行……比較。

ranked_indices = np.argsort(dense_scores)[::-1]
i = ranked_indices[0]

if dense_scores[i] > 0.5:
    print(f"Your question is: {user_question}")
    print(f"You can find answer from the sentence number {i}")
    print(f"The sentence is: {sentences[i]}")
else:
    print("no answer")

np.argsort 把得分排序並傳回它們的位置;[::-1] 把次序 倒轉,令最高分排在最前,而 ranked_indices[0] 就是勝出句子的編號。 接下來是重要的一環:程式只在最高得分超過 0.5 時才作答。如果檔案中 沒有任何句子夠接近,它會老實地印出 no answer,而不是亂猜。

完整程式

from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer('BAAI/bge-m3')

with open('sentences-restaurant.txt', 'r', encoding='utf-8') as f:
    sentences = [line.strip() for line in f.readlines() if line.strip()]

user_question = "What is your address?"

question_embedding = model.encode(user_question.strip().lower())
sentence_embeddings = model.encode([s.lower() for s in sentences])

dot_product = np.dot(sentence_embeddings, question_embedding)
dense_scores = dot_product / (np.linalg.norm(sentence_embeddings, axis=1) * np.linalg.norm(question_embedding))

ranked_indices = np.argsort(dense_scores)[::-1]
i = ranked_indices[0]

if dense_scores[i] > 0.5:
    print(f"Your question is: {user_question}")
    print(f"You can find answer from the sentence number {i}")
    print(f"The sentence is: {sentences[i]}")
else:
    print("no answer")

在自己的電腦上執行

下載 zip 檔案並 解壓到一個資料夾。這個 zip 包含程式、sentences-restaurant.txt 資料檔, 以及一個 pyproject.toml 專案檔案。在 Visual Studio Code 中開啟資料夾, 在終端機逐行輸入以下三行:

uv python pin 3.12.10
uv sync
uv run cos_similarity12_restaurant.py

第一行記錄這個資料夾使用哪個 Python 版本。第二行設定專案,並安裝程式需要的兩個 套件 sentence-transformers 和 numpy。第三行執行程式。 首次執行因要下載模型而需時較長;之後,答案幾秒內便會出現:

Similarity scores: [0.5011991  0.5202471  0.39348638]
Ranked indices: [1 0 2]
Your question is: What is your address?
You can find answer from the sentence number 1
The sentence is: Address : Unit 10, 2F, Festival Walk, Kowloon Tong

對照資料檔細看第一行:地址句子得 0.520 分,營業時間句子得 0.501 分——緊隨其後,因為營業時間同樣是實用的資料——而套餐句子得 0.393 分。 勝出者僅僅越過 0.5 門檻,這對如此簡短的問題來說很典型;內容更豐富的檔案 會把差距拉開。

如果你還未設定 uv,請先從 如何安裝 Visual Studio Code?開始,然後看 uv 筆記: Windows 或 Mac。

限制

延伸閱讀