Python编程:使用gensim对中文文本进行相似度计算
2023-09-14 09:07:15 时间
gensim文档:
https://radimrehurek.com/gensim/tutorial.html
安装
pip install gensim
代码示例
# -*- coding: utf-8 -*-
import logging
import jieba
from gensim import corpora, models, similarities
logging.basicConfig(level=logging.DEBUG)
jieba.setLogLevel(logging.INFO)
class DocumentSimilar(object):
def __init__(self, documents):
self.documents = documents
self.dictionary = None
self.tfidf = None
self.similar_matrix = None
self.calculate_similar_matrix()
@staticmethod
def split_word(document):
"""
分词,去除停用词
"""
stop_words = {":", "的", ",", "”"}
text = []
for word in jieba.cut(document):
if word not in stop_words:
text.append(word)
logging.debug(text)
return text
def calculate_similar_matrix(self):
"""
计算相似度矩阵及一些必要数据
"""
words = [self.split_word(document) for document in self.documents]
self.dictionary = corpora.Dictionary(words)
corpus = [self.dictionary.doc2bow(word) for word in words]
self.tfidf = models.TfidfModel(corpus)
corpus_tfidf = self.tfidf[corpus]
self.similar_matrix = similarities.MatrixSimilarity(corpus_tfidf)
def get_similar(self, document):
"""
计算要比较的文档与语料库中每篇文档的相似度
"""
words = self.split_word(document)
corpus = self.dictionary.doc2bow(words)
corpus_tfidf = self.tfidf[corpus]
return self.similar_matrix[corpus_tfidf]
if __name__ == '__main__':
documents = [
"货运物流供应商Flexport完成10亿美元融资",
"一笔300亿并购落地,一个新游戏帝国崛起",
"讯轻科技”累计完成近千万元融资",
"窝趣公寓完成近2亿元B轮融资主打品质和轻松社交的居住环境",
"IBM的区块链副总裁JesseLund:比特币将达到100万美元",
]
doc_similar = DocumentSimilar(documents)
# 要比较的文档
new_doc = "窝趣公寓完成近2亿元B轮融资"
for value, document in zip(doc_similar.get_similar(new_doc), documents):
print("{:.2f}".format(value), document)
输出结果
0.03 货运物流供应商Flexport完成10亿美元融资
0.00 一笔300亿并购落地,一个新游戏帝国崛起
0.10 讯轻科技”累计完成近千万元融资
0.66 窝趣公寓完成近2亿元B轮融资主打品质和轻松社交的居住环境
0.00 IBM的区块链副总裁JesseLund:比特币将达到100万美元
参考:
相关文章
- python的安装教程_Python的安装
- python 生成数组_Python创建数组「建议收藏」
- Python入门系列(五)一篇搞懂python语句
- Python入门系列(九)pip、try except、用户输入、字符串格式
- java和python哪个值得学-学java好还是Python好?
- 符合python命名规范的标识符是什么_Python标识符命名规范
- 迭代器Python_python进阶路线
- python selenium 实现自动化输入账号 word 邮箱
- 【说站】python协程函数如何执行
- 经纬度距离计算 python_Python已知两坐标求距离
- python to exe transporter: py2exe Test report「建议收藏」
- python图像多层小波分解_Python中图像小波分解与重构以及灰度图加噪
- Rpc接口测试_Python接口测试
- Python将数据写入txt文件_python将内容写入txt文件
- 【python】读取csv xlsx xlx txt文件 类
- 廖雪峰的 Python 教程_python基础教程廖雪pdf
- Python 异步: 使用和查询任务(8)
- python-数据库编程-如何在Python中连接到数据库
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(三)
- 网络工程师学Python-33-多线程技术简述
- Linux上的Python之旅(linux自带python)
- python之面向对象之封装详解编程语言
- python学习Linux、Python,体验自由的乐趣(lexlinux)
- 学习 Python 的 12 个方式
- Python脚本实现Linux系统管理及自动化部署(python写linux)