TextRank中文,英文关键词提取

1.基于pytextrank英文关键词提取
# pip install pytextrank
# python -m spacy download en_core_web_sm
import spacy
import pytextrank
text = "Compatibility of systems of linear constraints over the set of natural numbers. Criteria of compatibility of a system of linear Diophantine equations, strict inequations, and nonstrict inequations are considered. Upper bounds for components of a minimal set of solutions and algorithms of construction of minimal generating sets of solutions for all types of systems are given. These criteria and the corresponding algorithms for constructing a minimal supporting set of solutions can be used in solving all the considered types systems and systems of mixed types."

# load a spaCy model, depending on language, scale, etc.
nlp = spacy.load("en_core_web_sm")

# add PyTextRank to the spaCy pipeline
tr = pytextrank.TextRank()
nlp.add_pipe(tr.PipelineComponent, name="textrank", last=True)

doc = nlp(text)

# examine the top-ranked phrases in the document
for p in doc._.phrases:
    print("{:.4f} {:5d}  {}".format(p.rank, p.count, p.text))
    print(p.chunks)

2.基于Textrank4zh的中文关键词提取
"""
TextRank算法主要包括:关键词抽取、关键短语抽取、关键句抽取。

(1)关键词抽取(keyword extraction)
关键词抽取是指从文本中确定一些能够描述文档含义的术语的过程。对关键词抽取而言,用于构建顶点集的文本单元可以是句子中的一个或多个字;根据这些字之间的关系(比如:在一个框中同时出现)构建边。根据任务的需要,可以使用语法过滤器(syntactic filters)对顶点集进行优化。语法过滤器的主要作用是将某一类或者某几类词性的字过滤出来作为顶点集。

(2)关键短语抽取(keyphrase extration)
关键词抽取结束后,我们可以得到的N个关键词,在原始文本中相邻的关键词构成关键短语。因此,从get_keyphrases函数的源码中我们可以看到,它先调用get_keywords抽取关键词,然后分析关键词是否存在相邻的情况,最后确定哪些是关键短语。

(3)关键句抽取(sentence extraction)
句子抽取任务主要针对的是自动摘要这个场景,将每一个sentence作为一个顶点,根据两个句子之间的内容重复程度来计算他们之间的“相似度”,以这个相似度作为联系,由于不同句子之间相似度大小不一致,在这个场景下构建的是以相似度大小作为edge权重的有权图。
"""
# coding=utf-8
from textrank4zh import TextRank4Keyword, TextRank4Sentence
import jieba.analyse
from snownlp import SnowNLP
import pandas as pd
import numpy as np
 
#关键词抽取
def keywords_extraction(text):
    tr4w = TextRank4Keyword(allow_speech_tags=['n', 'nr', 'nrfg', 'ns', 'nt', 'nz'])
    # allow_speech_tags   --词性列表,用于过滤某些词性的词
    tr4w.analyze(text=text, window=2, lower=True, vertex_source='all_filters', edge_source='no_stop_words',
                 pagerank_config={'alpha': 0.85, })
    # text    --  文本内容,字符串
    # window  --  窗口大小,int,用来构造单词之间的边。默认值为2
    # lower   --  是否将英文文本转换为小写,默认值为False
    # vertex_source  -- 选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来构造pagerank对应的图中的节点
    #                -- 默认值为`'all_filters'`,可选值为`'no_filter', 'no_stop_words', 'all_filters'
    # edge_source  -- 选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来构造pagerank对应的图中的节点之间的边
    #              -- 默认值为`'no_stop_words'`,可选值为`'no_filter', 'no_stop_words', 'all_filters'`。边的构造要结合`window`参数
 
    # pagerank_config  -- pagerank算法参数配置,阻尼系数为0.85
    keywords = tr4w.get_keywords(num=6, word_min_len=2)
    # num           --  返回关键词数量
    # word_min_len  --  词的最小长度,默认值为1
    return keywords
 
#关键短语抽取
def keyphrases_extraction(text):
    tr4w = TextRank4Keyword()
    tr4w.analyze(text=text, window=2, lower=True, vertex_source='all_filters', edge_source='no_stop_words',
                 pagerank_config={'alpha': 0.85, })
    keyphrases = tr4w.get_keyphrases(keywords_num=6, min_occur_num=1)
    # keywords_num    --  抽取的关键词数量
    # min_occur_num   --  关键短语在文中的最少出现次数
    return keyphrases
 
#关键句抽取
def keysentences_extraction(text):
    tr4s = TextRank4Sentence()
    tr4s.analyze(text, lower=True, source='all_filters')
    # text    -- 文本内容,字符串
    # lower   -- 是否将英文文本转换为小写,默认值为False
    # source  -- 选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来生成句子之间的相似度。
    # 		  -- 默认值为`'all_filters'`,可选值为`'no_filter', 'no_stop_words', 'all_filters'
    # sim_func -- 指定计算句子相似度的函数
 
    # 获取最重要的num个长度大于等于sentence_min_len的句子用来生成摘要
    keysentences = tr4s.get_key_sentences(num=3, sentence_min_len=6)
    return keysentences
 
 
def keywords_textrank(text):
    keywords = jieba.analyse.textrank(text, topK=6)
    return keywords
 
 
if __name__ == "__main__":
    text = "来源:中国科学报本报讯(记者肖洁)又有一位中国科学家喜获小行星命名殊荣!4月19日下午,中国科学院国家天文台在京举行“周又元星”颁授仪式," \
           "我国天文学家、中国科学院院士周又元的弟子与后辈在欢声笑语中济济一堂。国家天文台党委书记、" \
           "副台长赵刚在致辞一开始更是送上白居易的诗句:“令公桃李满天下,何须堂前更种花。”" \
           "据介绍,这颗小行星由国家天文台施密特CCD小行星项目组于1997年9月26日发现于兴隆观测站," \
           "获得国际永久编号第120730号。2018年9月25日,经国家天文台申报," \
           "国际天文学联合会小天体联合会小天体命名委员会批准,国际天文学联合会《小行星通报》通知国际社会," \
           "正式将该小行星命名为“周又元星”。"
    #关键词抽取
    keywords=keywords_extraction(text)
    print(keywords)
 
    #关键短语抽取
    keyphrases=keyphrases_extraction(text)
    print(keyphrases)
 
    #关键句抽取
    keysentences=keysentences_extraction(text)
    print(keysentences)



参考:
https://pypi.org/project/pytextrank/
https://blog.csdn.net/asialee_bird/article/details/96894533

  • 4
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
TextRank算法是一种无监督的关键词提取算法,它利用图论的PageRank算法进行关键词的计算。其基本思想是:将文本的每个句子看成图的一个节点,句子之间的相似度看成边,通过迭代的方式计算出每个节点的重要性,从而得到关键词TextRank算法提取关键词的流程: 1. 对文本进行分句,将每个句子看成图的一个节点; 2. 对每个句子进行分词,去除停用词和无意义的词,只保留名词、动词、形容词等关键词; 3. 构建句子之间的相似度矩阵,相似度的计算可以使用余弦相似度等算法; 4. 将相似度矩阵转化为权重矩阵,使用PageRank算法进行迭代计算,得到每个节点的重要性得分; 5. 对每个句子的重要性得分进行排序,取得分最高的几个句子作为关键词。 下面是使用Python实现TextRank算法提取关键词的示例代码: ```python import jieba import jieba.analyse import numpy as np import networkx as nx # 加载停用词 stopwords = set() with open('stopwords.txt', 'r', encoding='utf-8') as f: for line in f: stopwords.add(line.strip()) # 加载文本数据 with open('input.txt', 'r', encoding='utf-8') as f: text = f.read() # 分句 sentences = text.split('。') # 分词,并去除无意义的词 keywords = [] for sentence in sentences: words = jieba.analyse.textrank(sentence, topK=10, withWeight=True, allowPOS=('n', 'v', 'a')) words = [(word, weight) for word, weight in words if word not in stopwords] keywords.extend(words) # 构建相似度矩阵 similarity_matrix = np.zeros((len(sentences), len(sentences))) for i in range(len(sentences)): for j in range(len(sentences)): if i != j: s1 = set(jieba.cut(sentences[i])) s2 = set(jieba.cut(sentences[j])) similarity_matrix[i][j] = len(s1 & s2) / (len(s1) + len(s2)) # 构建权重矩阵,使用PageRank算法进行计算 nx_graph = nx.from_numpy_matrix(similarity_matrix) scores = nx.pagerank(nx_graph) # 按得分排序,取前N个关键词 keywords = sorted(keywords, key=lambda x: scores[sentences.index(x[0])], reverse=True)[:10] # 输出结果 with open('output.txt', 'w', encoding='utf-8') as f: for keyword, weight in keywords: f.write(keyword + '\t' + str(weight) + '\n') ``` 需要注意的是,这里使用了jieba库的`textrank`函数进行关键词提取,也可以使用其他方法进行分词和关键词提取。同时,相似度矩阵的计算方法也可以根据具体需求进行调整。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cocktail_py

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值