【自然语言处理】利用TextRank算法提取关键词

article/2025/8/28 14:34:04

利用TextRank提取关键词

TextRank 是一种基于 PageRank 的算法,常用于关键词提取和文本摘要。在本文中,我将通过一个关键字提取示例帮助您了解 TextRank 如何工作,并展示 Python 的实现。

使用 TextRank、NER 等进行关键词提取

1.PageRank简介

关于 PageRank 的文章有很多,我只简单介绍一下 PageRank。这将有助于我们稍后理解 TextRank,因为它是基于 PageRank 的。

PageRank (PR) 是一种用于计算网页权重的算法。我们可以把所有的网页看成一个大的有向图。在此图中,节点是网页。如果网页 A 有指向网页 B 的链接,则它可以表示为从 A 到 B 的有向边。

构建完整个图后,我们可以通过以下公式为网页分配权重。
在这里插入图片描述
在这里插入图片描述
这是一个示例,可以更好地理解上面的符号。我们有一个图表来表示网页如何相互链接。每个节点代表一个网页,箭头代表边。我们想得到网页 e 的权重。

我们可以将上述函数中的求和部分重写为更简单的版本。
在这里插入图片描述
我们可以通过下面的函数得到网页 e 的权重。
在这里插入图片描述
我们可以看到网页 e 的权重取决于其入站页面的权重。我们需要多次运行此迭代才能获得最终权重。初始化时,每个网页的重要性为 1。

2.PageRank实现

在这里插入图片描述
我们可以用一个矩阵来表示图中 a、b、e、f 之间的入站和出站链接。
在这里插入图片描述
一行中的每个节点表示来自其他节点的入站链接。例如,对于 e 行,节点 a 和 b 具有指向节点 e 的出站链接。本演示文稿将简化更新权重的计算。

根据 1 ∣ O u t ( V i ) ∣ \frac{1}{|Out(Vi)|} Out(Vi)1,从函数中,我们应该规范化每一列。
在这里插入图片描述
我们使用这个矩阵乘以所有节点的权重。
在这里插入图片描述
这只是一次没有阻尼系数 d 的迭代。
在这里插入图片描述
我们可以使用 Python 进行多次迭代。

import numpy as np
g = [[0, 0, 0, 0],[0, 0, 0, 0],[1, 0.5, 0, 0],[0, 0.5, 0, 0]]g = np.array(g)
pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1
d = 0.85for iter in range(10):pr = 0.15 + 0.85 * np.dot(g, pr)print(iter)print(pr)
0
[0.15 0.15 1.425 0.575]
1
[0.15 0.15 0.34125 0.21375]
2
[0.15 0.15 0.34125 0.21375]
3
[0.15 0.15 0.34125 0.21375]
4
[0.15 0.15 0.34125 0.21375]
5
[0.15 0.15 0.34125 0.21375]
6
[0.15 0.15 0.34125 0.21375]
7
[0.15 0.15 0.34125 0.21375]
8
[0.15 0.15 0.34125 0.21375]
9
[0.15 0.15 0.34125 0.21375]
10
[0.15 0.15 0.34125 0.21375]

所以 e 的权重(PageRank值)为 0.34125。

如果我们把有向边变成无向边,我们就可以相应地改变矩阵。
在这里插入图片描述
规范化。

在这里插入图片描述
我们应该相应地更改代码。

import numpy as np
g = [[0, 0, 0.5, 0],[0, 0, 0.5, 1],[1, 0.5, 0, 0],[0, 0.5, 0, 0]]g = np.array(g)
pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1
d = 0.85for iter in range(10):pr = 0.15 + 0.85 * np.dot(g, pr)print(iter)print(pr)
0
[0.575 1.425 1.425 0.575]
1
[0.755625 1.244375 1.244375 0.755625]
2
[0.67885937 1.32114062 1.32114062 0.67885937]
3
[0.71148477 1.28851523 1.28851523 0.71148477]
4
[0.69761897 1.30238103 1.30238103 0.69761897]
5
[0.70351194 1.29648806 1.29648806 0.70351194]
6
[0.70100743 1.29899257 1.29899257 0.70100743]
7
[0.70207184 1.29792816 1.29792816 0.70207184]
8
[0.70161947 1.29838053 1.29838053 0.70161947]
9
[0.70181173 1.29818827 1.29818827 0.70181173]

所以 e 的权重(PageRank值)为 1.29818827。

3.TextRank原理

TextRank 和 PageTank 有什么区别呢?

简而言之 PageRank 用于网页排名,TextRank 用于文本排名。 PageRank 中的网页就是 TextRank 中的文本,所以基本思路是一样的。

我们将一个文档分成几个句子,我们只存储那些带有特定 POS 标签的词。我们使用 spaCy 进行词性标注。

import spacy
nlp = spacy.load('en_core_web_sm')content = '''
The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.
'''doc = nlp(content)
for sents in doc.sents:print(sents.text)

我们将段落分成三个句子。

The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics.At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking.While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.

因为句子中的大部分词对确定重要性没有用,我们只考虑带有 NOUN、PROPN、VERB POS 标签的词。这是可选的,你也可以使用所有的单词。

candidate_pos = ['NOUN', 'PROPN', 'VERB']
sentences = []for sent in doc.sents:selected_words = []for token in sent:if token.pos_ in candidate_pos and token.is_stop is False:selected_words.append(token)sentences.append(selected_words)print(sentences)
[[Wandering, Earth, described, China, budget, science, fiction, thriller, screens, AMC, theaters, North, America, weekend, shows, filmmaking, focused, spectacles, China, epics], 
[time, Wandering, Earth, feels, throwback, eras, filmmaking], 
[film, cast, setting, tone, science, fiction, fans, going, lot, screen, reminds, movies]]

每个词都是 PageRank 中的一个节点。我们将窗口大小设置为 k。
在这里插入图片描述
[ w 1 , w 2 , … , w k ] , [ w 2 , w 3 , … , w k + 1 ] , [ w 3 , w 4 , … , w k + 2 ] [w1, w2, …, w_k], [w2, w3, …, w_{k+1}], [w3, w4, …, w_{k+2}] [w1,w2,,wk],[w2,w3,,wk+1],[w3,w4,,wk+2] 是窗口。窗口中的任何两个词对都被认为具有无向边。

我们以 [time, wandering, earth, feels, throwback, era, filmmaking] 为例,设置窗口大小 k = 4 k=4 k=4,所以得到 4 个窗口,[time, Wandering, Earth, feels][Wandering, Earth, feels, throwback][Earth, feels, throwback, eras][feels, throwback, eras, filmmaking]

对于窗口 [time, Wandering, Earth, feels],任何两个词对都有一条无向边。所以我们得到 (time, Wandering)(time, Earth)(time, feels)(Wandering, Earth)(Wandering, feels)(Earth, feels)

基于此图,我们可以计算每个节点(单词)的权重。最重要的词可以用作关键字。

4.TextRank提取关键词

这里我用 Python 实现了一个完整的例子,我们使用 spaCy 来获取词的词性标签。

from collections import OrderedDict
import numpy as np
import spacy
from spacy.lang.en.stop_words import STOP_WORDSnlp = spacy.load('en_core_web_sm')class TextRank4Keyword():"""Extract keywords from text"""def __init__(self):self.d = 0.85 # damping coefficient, usually is .85self.min_diff = 1e-5 # convergence thresholdself.steps = 10 # iteration stepsself.node_weight = None # save keywords and its weightdef set_stopwords(self, stopwords):  """Set stop words"""for word in STOP_WORDS.union(set(stopwords)):lexeme = nlp.vocab[word]lexeme.is_stop = Truedef sentence_segment(self, doc, candidate_pos, lower):"""Store those words only in cadidate_pos"""sentences = []for sent in doc.sents:selected_words = []for token in sent:# Store words only with cadidate POS tagif token.pos_ in candidate_pos and token.is_stop is False:if lower is True:selected_words.append(token.text.lower())else:selected_words.append(token.text)sentences.append(selected_words)return sentencesdef get_vocab(self, sentences):"""Get all tokens"""vocab = OrderedDict()i = 0for sentence in sentences:for word in sentence:if word not in vocab:vocab[word] = ii += 1return vocabdef get_token_pairs(self, window_size, sentences):"""Build token_pairs from windows in sentences"""token_pairs = list()for sentence in sentences:for i, word in enumerate(sentence):for j in range(i+1, i+window_size):if j >= len(sentence):breakpair = (word, sentence[j])if pair not in token_pairs:token_pairs.append(pair)return token_pairsdef symmetrize(self, a):return a + a.T - np.diag(a.diagonal())def get_matrix(self, vocab, token_pairs):"""Get normalized matrix"""# Build matrixvocab_size = len(vocab)g = np.zeros((vocab_size, vocab_size), dtype='float')for word1, word2 in token_pairs:i, j = vocab[word1], vocab[word2]g[i][j] = 1# Get Symmeric matrixg = self.symmetrize(g)# Normalize matrix by columnnorm = np.sum(g, axis=0)g_norm = np.divide(g, norm, where=norm!=0) # this is ignore the 0 element in normreturn g_normdef get_keywords(self, number=10):"""Print top number keywords"""node_weight = OrderedDict(sorted(self.node_weight.items(), key=lambda t: t[1], reverse=True))for i, (key, value) in enumerate(node_weight.items()):print(key + ' - ' + str(value))if i > number:breakdef analyze(self, text, candidate_pos=['NOUN', 'PROPN'], window_size=4, lower=False, stopwords=list()):"""Main function to analyze text"""# Set stop wordsself.set_stopwords(stopwords)# Pare text by spaCydoc = nlp(text)# Filter sentencessentences = self.sentence_segment(doc, candidate_pos, lower) # list of list of words# Build vocabularyvocab = self.get_vocab(sentences)# Get token_pairs from windowstoken_pairs = self.get_token_pairs(window_size, sentences)# Get normalized matrixg = self.get_matrix(vocab, token_pairs)# Initionlization for weight(pagerank value)pr = np.array([1] * len(vocab))# Iterationprevious_pr = 0for epoch in range(self.steps):pr = (1-self.d) + self.d * np.dot(g, pr)if abs(previous_pr - sum(pr))  < self.min_diff:breakelse:previous_pr = sum(pr)# Get weight for each nodenode_weight = dict()for word, index in vocab.items():node_weight[word] = pr[index]self.node_weight = node_weight

这个 TextRank4Keyword 实现了前文描述的相关功能。我们可以看到一段的输出。

text = '''
The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.
'''
​
tr4w = TextRank4Keyword()
tr4w.analyze(text, candidate_pos = ['NOUN', 'PROPN'], window_size=4, lower=False)
tr4w.get_keywords(10)
science - 1.717603106506989
fiction - 1.6952610926181002
filmmaking - 1.4388798751402918
China - 1.4259793786986021
Earth - 1.3088154732297723
tone - 1.1145002295684114
Chinese - 1.0996896235078055
Wandering - 1.0071059904601571
weekend - 1.002449354657688
America - 0.9976329264870932
budget - 0.9857269586649321
North - 0.9711240881032547

http://chatgpt.dhexx.cn/article/TWol8RGx.shtml

相关文章

【NLP】关键词提取:TFIDF、TextRank

前两天看到论文《Chinese Poetry Generation with Planning based Neural Network》中使用TextRank进行关键词提取。在阅读文章时也想到了除了TextRank之外&#xff0c;经常还使用TFIDF进行关键词提取。 一些算法的使用取决于业务场景和算法的特性。关键词提取是干什么的呢&am…

TF-IDF算法和TextRank算法的分析比较

TF-IDF算法 TF-IDF&#xff08;词频-逆文档频率&#xff09;算法是一种统计方法&#xff0c;用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加&#xff0c;但同时会随着它在语料库中出现的频率成反比下降…

Python文本处理工具——TextRank

背景 TextRank是用与从文本中提取关键词的算法&#xff0c;它采用了PageRank算法&#xff0c;原始的论文在这里。Github地址。 这个工具使用POS( part-of-speech tagging : 词性标注 )然后抽取名词&#xff0c;这种方法对于关键词提取独具特色。 注意&#xff1a; 先安装NL…

TextRank学习笔记

TextRank起源与PageRank TextRank的灵感来源于大名鼎鼎的PageRank算法&#xff0c;这是一个用作网页重要度排序的算法。 并且&#xff0c;这个算法也是基于图的&#xff0c;每个网页可以看作是一个图中的结点&#xff0c;如果网页A能够跳转到网页B&#xff0c;那么则有一条A-…

【TextRank】关键词提取 算法原理 公式推导 源码分析

1.前言 在介绍TextRank前&#xff0c;我想先给大家介绍下PageRank&#xff0c;实质上个人认为可以把TextRank当做PageRank2.0。 谷歌的两位创始人的佩奇和布林&#xff0c;借鉴了学术界评判学术论文重要性的通用方法&#xff0c;“那就是看论文的引用次数”。由此想到网页的重要…

NLP - 关键词提取 - TextRank

NLP - 关键词提取 - TextRank 一、TextRank介绍二、PageRank介绍三、PageRank计算过程四、关键词提取任务 一、TextRank介绍 TextRank算法则可以脱离语料库的基础&#xff0c;仅对单篇文档进行分析就可以提取该文档的关键词。这也是TextRank算法的重要特点。TextRank算法的基本…

textrank算法原理与提取关键词、自动提取摘要PYTHON

首先介绍原理与概念 TextRank 算法是一种用于文本的基于图的排序算法。其基本思想来源于谷歌的 PageRank算法&#xff08;其原理在本文在下面&#xff09;, 通过把文本分割成若干组成单元(单词、句子)并建立图模型, 利用投票机制对文本中的重要成分进行排序, 仅利用单篇文档本…

TextRank算法总结

TextRank算法总结 最近在调研自动生成文本方面的内容&#xff0c;突然想到了自动文摘里的textRank&#xff0c;这里我将参考了一些资料并对这些知识点进行了整理总结&#xff0c;初步总结如下&#xff1a; 目录 PageRank简介基于TextRank的关键词提取基于TextRank的关键词短语提…

TextRank算法实践

TextRank算法实践 PageRank算法思想 TextRank算法的思想主要源于PageRank算法&#xff0c;PageRank算法主要用于给互联网网页排序&#xff0c;根据网页之间的跳转来构造一个初始权重矩阵&#xff08;转移矩阵&#xff09;&#xff0c;默认每个网页质量都是1 使用一个向量v&…

TextRank算法的基本原理及textrank4zh使用实例

TextRank算法是一种文本排序算法,由谷歌的网页重要性排序算法PageRank算法改进而来,它能够从一个给定的文本中提取出该文本的关键词、关键词组,并使用抽取式的自动文摘方法提取出该文本的关键句。其提出论文是: Mihalcea R, Tarau P. TextRank: Bringing order into texts[…

TextRank算法

TextRank算法理解 TextRank算法 TextRank算法基于PageRank&#xff0c;用于为文本生成关键字和摘要。其论文是&#xff1a; Mihalcea R, Tarau P. TextRank: Bringing order into texts[C]. Association for Computational Linguistics, 2004. 先从PageRank讲起 在浅入浅出…

TextRank

TextRank与PageRank TextRank的灵感来源于大名鼎鼎的PageRank算法&#xff0c;这是一个用作网页重要度排序的算法。 这个算法是基于图的&#xff0c;每个网页可以看作是一个图中的结点&#xff0c;如果网页A能够跳转到网页B&#xff0c;那么则有一条A->B的有向边。这样&am…

TextRank算法介绍及实现

目录 1、PageRank算法 2、TextRank算法 &#xff08;1&#xff09;关键词抽取&#xff08;keyword extraction&#xff09; &#xff08;2&#xff09;关键短语抽取&#xff08;keyphrase extration&#xff09; &#xff08;3&#xff09;关键句抽取&#xff08;sentence…

TextRank原理解释

目录 1. PageRank原理 2. TextRank &#xff08;1&#xff09;TextRank需要满足的条件 &#xff08;2&#xff09;TextRank思想的简要理解 &#xff08;3&#xff09;TextRank原理及例子讲解 1. PageRank原理 在这里可以看我转载的PageRank原理链接&#xff0c;比较详细h…

TextRank算法原理简析、代码实现

前言—PageRank 注&#xff1a;PageRank原理另行查询 在介绍TextRank前&#xff0c;我想先给大家介绍下PageRank&#xff0c;实质上个人认为可以把TextRank当做PageRank2.0。   谷歌的两位创始人的佩奇和布林&#xff0c;借鉴了学术界评判学术论文重要性的通用方法&#xff0…

NLP学习笔记——TextRank算法

一、算法简介 TextRank算法是一种基于图的排序算法&#xff0c;由谷歌的网页重要性排序算法PageRank算法改进而来&#xff0c;主要应用有关键词提取、文本摘要抽取等。该算法的主要思想是&#xff1a;把文档中的词&#xff08;句&#xff09;看成一个网络&#xff0c;词&#…

机器学习——逻辑回归常见面试题整理

逻辑回归 1.介绍 逻辑回归假设数据服从伯努利分布&#xff0c;通过极大化似然函数的方法&#xff0c;运用梯队下降来求解参数&#xff0c;来达到将数据二分类的目的。 2.逻辑回归的损失函数和梯度下降参数迭代方法 逻辑回归的损失函数是它的极大似然函数 参数迭代方法 3.逻…

面试精选逻辑推理题总结

类似的杀人游戏 1、500张骨牌整齐地排成一行&#xff0c;按顺序编号为1、2、3、……、499、500。第一次拿走所有奇数位置上的骨牌&#xff0c;第二次再从剩余骨牌中拿走奇数位置上的骨牌&#xff0c;以此类推。请问最后剩下的一张骨牌的编号是&#xff1f;&#xff08;256&…

IT科技企业逻辑思维面试题

逻辑思维面试题 一、假设有一个池塘&#xff0c;里面有无穷多的水。现有2个空水壶&#xff0c;容积分别为5升和6升。问题是如何只用这2个水壶从池塘里取得3升的水。【请描述操作过程】 答&#xff1a;&#xff08;1&#xff09;先用容积为6升的水壶装满水&#xff1b; &#…

面试逻辑题分享--字母数字映射关系推算题

越来越多的朋友可能会发现&#xff0c;在现在找工作的时候&#xff0c;经常会遇到一些笔试题&#xff0c;而且其中不乏有逻辑题&#xff0c;企业希望通过一些逻辑题的测试&#xff0c;来判断求职者的一个逻辑思维能力。今晚在群里看到有小伙伴发了一个题&#xff0c;一时兴起&a…