gensim进行LSI LSA LDA主题模型,TFIDF关键词提取,jieba TextRank关键词提取代码实现示例

本文通过gensim库详细介绍了如何使用LSI, LSA和LDA进行主题建模,并结合TFIDF和jieba的TextRank算法进行了关键词提取的代码示例,帮助读者理解并实践文本分析技术。" 135742727,5632965,SCConv:YOLOv8目标检测中的空间与通道重构卷积,"['目标检测', '卷积神经网络', 'YOLO', 'SCConv']
摘要由CSDN通过智能技术生成
import gensim
import math
import jieba
import jieba.posseg as posseg
from jieba import analyse
from gensim import corpora, models
import functools
import numpy as np


# 停用词表加载方法
# 停用词表存储路径,每一行为一个词,按行读取进行加载
# 进行编码转换确保匹配准确率
def get_stopword_list():
    stopword_path = '.\\stopword.txt'
    stopword_list = [sw.replace('\n', '') for sw in open(stopword_path, encoding='utf8').readlines()]
    return stopword_list


# 分词方法,调用结巴接口
def seg_to_list(sentence, pos=False):
    if not pos:
        # 不进行词性标注分词
        seg_list = jieba.cut(sentence)
    else:
        # 进行词性标注分词
        seg_list = posseg.cut(sentence)

    return seg_list


# 去除干扰词
def word_filter(seg_list, pos=False):
    stopword_list = get_stopword_list()
    filter_list = []
    # 根据POS参数选择是否词性过滤
    # 不进行词性过滤,则将词性都标记为n,表示全部保留
    for seg in seg_list:
        if not pos:
            word = seg
            flag = 'n'
        else:
            word = seg.word
            flag = seg.flag
        if not flag.startswith('n'):
            continue
        # 过滤停用词表中的词,以及长度为<2的词
        if word not in stopword_list and len(word) > 1:
            filter_list.append(word)
    return filter_list


# 数据加载,pos为是否词性标注的参数,corpus_path为数据集路径
def load_data(pos=False, corpus_path='.\\corpus.txt'):
    # 调用上面方式对数据集进行处理,处理后的每条数据仅保留非干扰词
    doc_list = []
    for line in open(corpus_path,  'r', encoding='utf8'):
        content = line.strip()
        seg_list = seg_to_list(content, pos)
        filter_list = word_filter(seg_list, pos)
        doc_list.append(filter_list)

    return doc_list


# idf值统计方法
def train_idf(doc_list):
    idf_dic = {}
    # 总文档数
    tt_count = len(doc_list)

    # 每个词出现的文档数  集合是去重的
    for doc in doc_list:
        for word in set(doc):  # 这是一个集合 这个很关键  集合是去重的
            idf_dic[word] = idf_dic.get(word, 0.0)+1.0

    # 按公式转换为idf值,分母加1进行平滑处理
    for k, v in idf_dic.items():
        idf_dic[k] = math.log(tt_count/(v+1.0))

    # 对于没有在字典中的词,默认其仅在一个文档出现,得到默认idf值
    default_idf = math.log(tt_count/1.0)
    return idf_dic, default_idf


#  排序函数,用于topK关键词的按值排序
def cmp(e1,
  • 10
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
抱歉,我不能直接给出代码而不解释。这些算法和关键词提取都需要一定的理论基础和实现细节,不能仅仅靠代码就能完整地理解。以下是对每个算法的简单介绍和示范代码LSA/LSI算法: LSA(潜在语义分析)或 LSI(潜在语义索引)算法是一种基于奇异值分解(SVD)的文本降维技术。它将文本转换为数学矩阵,然后通过SVD来找到最重要的主题(主成分),从而达到降维的目的。关键词提取可以通过计算文本中每个单词与主题之间的相似度来实现。 以下是一个使用Python的gensim实现LSI算法的示例代码: ```python from gensim import corpora, models # 读取文本文件,将每行作为一个文档 with open('text.txt', 'r') as f: documents = [line.strip() for line in f] # 建立词典 dictionary = corpora.Dictionary([doc.split() for doc in documents]) # 将每个文档转换为向量表示 corpus = [dictionary.doc2bow(doc.split()) for doc in documents] # 训练模型并将文档投影到主题空间 lsi_model = models.LsiModel(corpus, num_topics=10, id2word=dictionary) corpus_lsi = lsi_model[corpus] # 输出每个文档的关键词 for i, doc in enumerate(corpus_lsi): keywords = sorted(doc, key=lambda x: x[1], reverse=True)[:5] print(f"Document {i+1} keywords:", [dictionary[word[0]] for word in keywords]) ``` LDA算法: LDA(Latent Dirichlet Allocation)算法是一种无监督的主题模型算法。它假设每个文档都由多个主题组成,每个主题又由多个单词组成。通过对文本中的单词进行聚类,LDA算法可以得到每个主题的单词分布和每个文档的主题分布。关键词提取可以通过计算每个主题中单词的重要性来实现。 以下是一个使用Python的gensim实现LDA算法的示例代码: ```python from gensim import corpora, models # 读取文本文件,将每行作为一个文档 with open('text.txt', 'r') as f: documents = [line.strip() for line in f] # 建立词典 dictionary = corpora.Dictionary([doc.split() for doc in documents]) # 将每个文档转换为向量表示 corpus = [dictionary.doc2bow(doc.split()) for doc in documents] # 训练模型并将文档投影到主题空间 lda_model = models.LdaModel(corpus, num_topics=10, id2word=dictionary) corpus_lda = lda_model[corpus] # 输出每个主题关键词 for i in range(10): keywords = lda_model.show_topic(i, topn=5) print(f"Topic {i+1} keywords:", [keyword[0] for keyword in keywords]) ``` 关键词提取关键词提取是一种从文本中自动提取关键词的技术。常用的方法包括TF-IDF、TextRank等。以下是一个使用Python的gensim实现TF-IDF关键词提取示例代码: ```python from gensim import corpora, models # 读取文本文件,将每行作为一个文档 with open('text.txt', 'r') as f: documents = [line.strip() for line in f] # 建立词典 dictionary = corpora.Dictionary([doc.split() for doc in documents]) # 将每个文档转换为向量表示 corpus = [dictionary.doc2bow(doc.split()) for doc in documents] # 计算TF-IDF权重 tfidf_model = models.TfidfModel(corpus) corpus_tfidf = tfidf_model[corpus] # 输出每个文档的关键词 for i, doc in enumerate(corpus_tfidf): keywords = sorted(doc, key=lambda x: x[1], reverse=True)[:5] print(f"Document {i+1} keywords:", [dictionary[word[0]] for word in keywords]) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值