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()
#將結果寫入文件
2019年4月15日