Skip to main content
 首页 » 编程设计

python之在 python 中使用 Tf-Idf 的搜索引擎

2025年05月04日10java哥

这是我的代码

 from sklearn.feature_extraction.text import TfidfVectorizer 
 corpus = [ 
     "this is first document ","this is second document","this is third","which document is first", ] 
 
 vectorizer = TfidfVectorizer() 
 
X = vectorizer.fit_transform(corpus) 
 
X.toarray() 

现在 这就是我想要做的?

当我搜索 document 时,它应该给我 [ 1,2,4]documents(sentence)

当我搜索第一个文档时,它应该给我 [1]documents(sentence)

当我搜索 second 时,它应该给我 [2]documents(sentence)

我想用 TfIdf 做这个(我不能做正常的搜索)

我该怎么做?

请您参考如下方法:

首先,您必须问自己一个问题:TfidfVectorizer 的作用是什么?答案是:它将您的文档转换为矢量。你怎么能进一步?一种解决方案是使用矢量化器将您的查询也转换为矢量。然后,您可以比较转换后的查询向量与数据库中文档的每个向量之间的余弦相似度。与查询向量余弦相似度最高的文档是最相关的文档(至少根据向量空间模型)。 这里https://towardsdatascience.com/tf-idf-for-document-ranking-from-scratch-in-python-on-real-world-dataset-796d339a4089是一个示例实现。