写一个Python程序,实现基于向量空间模型理论,构造一定数量的文本库,采用TFIDF权重进行关键词排序选择,并采用向量夹角余弦判断检索词和文本库中文本的相似度。
时间: 2024-02-15 22:04:24 浏览: 25
以下是一个简单的Python程序,实现基于向量空间模型理论的文本检索:
```python
import math
# 构造文本库
corpus = ['I love programming', 'Programming is fun', 'Coding is my passion', 'Python is my favorite language']
# 计算每个文本中每个词的TF值
def compute_tf(text):
tf_text = {}
for word in text.split():
tf_text[word] = tf_text.get(word, 0) + 1
for word in tf_text:
tf_text[word] = tf_text[word] / float(len(text.split()))
return tf_text
# 计算每个文本中每个词的IDF值
def compute_idf(word, corpus):
return math.log10(len(corpus) / sum([1.0 for i in corpus if word in i]))
# 计算每个文本中每个词的TF-IDF值
def compute_tfidf(text, corpus):
tfidf_text = {}
tf_text = compute_tf(text)
for word in tf_text:
idf = compute_idf(word, corpus)
tfidf_text[word] = tf_text[word] * idf
return tfidf_text
# 计算向量夹角余弦
def cosine_similarity(text1, text2):
tfidf1 = compute_tfidf(text1, corpus)
tfidf2 = compute_tfidf(text2, corpus)
numerator = 0
denominator1 = 0
denominator2 = 0
for word in tfidf1:
numerator += tfidf1[word] * tfidf2.get(word, 0)
denominator1 += tfidf1[word] ** 2
for word in tfidf2:
denominator2 += tfidf2[word] ** 2
denominator = math.sqrt(denominator1) * math.sqrt(denominator2)
if not denominator:
return 0.0
else:
return float(numerator) / denominator
# 测试检索
query = 'Python programming'
scores = []
for doc in corpus:
sim_score = cosine_similarity(query, doc)
scores.append((sim_score, doc))
scores.sort(reverse=True)
for score, doc in scores:
print(f"相似度:{score:.3f}\t文本:{doc}")
```
在这个程序中,我们首先构造了一个文本库,然后使用TF-IDF权重计算每个文本中每个词的重要性,最后使用余弦相似度计算查询文本和每个文本之间的相似度,并按相似度从高到低排序输出结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)