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。

局限

延伸阅读