用python代码实现文档之间的相似性比对
时间: 2024-05-09 13:20:34 浏览: 9
以下是使用Python中的gensim和nltk库实现文档相似性比对的示例代码:
```python
import gensim
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from string import punctuation
# 加载停用词
stop_words = set(stopwords.words('english') + list(punctuation))
# 定义函数:文本预处理
def preprocess(text):
tokens = word_tokenize(text.lower())
tokens = [token for token in tokens if token not in stop_words]
return tokens
# 加载文档
doc1 = "This is the first document."
doc2 = "This is the second document."
doc3 = "This is the third document."
# 预处理文档
processed_docs = [preprocess(doc) for doc in [doc1, doc2, doc3]]
# 构建词典
dictionary = gensim.corpora.Dictionary(processed_docs)
# 构建语料库
corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
# 训练TF-IDF模型
tfidf = gensim.models.TfidfModel(corpus)
# 计算每个文档的相似性
index = gensim.similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=len(dictionary))
sims = index[tfidf[corpus]]
# 打印相似性结果
print(list(enumerate(sims)))
```
该代码将文档进行预处理后,构建了一个词典和语料库,并使用TF-IDF模型计算了每个文档的相似性。最后,结果以列表的形式打印出来。