版权声明:版权所有 https://blog.csdn.net/weixin_43907422/article/details/89322288
python基于余弦相似度Cosine Similarity的检索系统
下面是源码,不足之处请提出并指正:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import jieba
x = input("输入关键词:")
#输入查询关键词
seg_list1 = jieba.cut(x, cut_all=True)
a = "/".join(seg_list1)
a = a.split("/")
listx = list(a)
#查询关键词分词
result = []
#定义存储结果的列表
file = open("text.txt", encoding = 'utf-8')
#导入目标文件
for line in file:
y = line
seg_list2 = jieba.cut(y, cut_all=True)
b = "/".join(seg_list2)
b = b.split("/")
listy = list(b)
#文件按行分割并分词
setx = list(set(listx))
sety = list(set(listy))
set1 = set(listx + listy)
countx = []
county = []
for i in set1:
countx.append((listx.count(i) / len(listx)) * (1 / (setx.count(i) + sety.count(i))))
county.append((listy.count(i) / len(listy)) * (1 / (setx.count(i) + sety.count(i))))
sim1 = 0
temp1 = 0
#余弦相似度分子部分结果
temp2 = 0
#余弦相似度分母部分结果
for k in range(len(set1)):
sim1 += countx[k] * county[k]
temp1 += (countx[k]) ** 2
temp2 += (county[k]) ** 2
sim2 = temp1 ** (1 / 2) * temp2 ** (1 / 2)
sim = sim1 / sim2
#余弦相似度计算过程
result.append([sim, line])
#结果载入列表
file.close()
#读取操作结束
result.sort()
result = result[::-1]
#相似度降序排名
result = result[0:10]
#取相似度前10名
f = open('result.txt', 'w')
for i in range(10):
f.write(result[i][1] + "\n")
f.close()
#将结果写入文件