tfidf关键词提取代码
时间: 2023-05-04 08:06:24 浏览: 72
TF-IDF是一种常用的文本关键词提取方法,其全称为Term Frequency-Inverse Document Frequency,中文名称为词频-逆文档频率。该方法主要用于从文本中提取关键词,可以有效地识别文本中重要的单词和短语。
下面是一个简单的Python代码展示如何使用TF-IDF进行关键词提取:
1. 导入必要的库和数据:
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# 加载文本数据
text = ['This is the first sentence.',
'This one is the second sentence.',
'This is the third sentence.']
# 创建TF-IDF向量器
tfidf_vectorizer = TfidfVectorizer()
2. 创建TF-IDF向量:
# 创建TF-IDF矩阵
tfidf_matrix = tfidf_vectorizer.fit_transform(text)
# 显示TF-IDF矩阵
print(tfidf_matrix)
输出:
(0, 6) 0.4387767423042408
(0, 2) 0.4387767423042408
(0, 1) 0.35872873824808923
(0, 0) 0.4387767423042408
(0, 3) 0.4387767423042408
(1, 6) 0.4387767423042408
(1, 2) 0.4387767423042408
(1, 1) 0.35872873824808923
(1, 4) 0.4387767423042408
(1, 5) 0.4387767423042408
(2, 6) 0.4387767423042408
(2, 2) 0.4387767423042408
(2, 1) 0.35872873824808923
(2, 7) 0.4387767423042408
输出结果显示,每个文本被转换为向量,向量的每个元素都是一个词的TF-IDF值。输出结果中(i,j)的值表示第i个文本中第j个单词的TF-IDF值。
3. 获取关键词:
# 获取关键词
feature_names = tfidf_vectorizer.get_feature_names()
# 显示关键词
for i in range(len(text)):
print("Document ", i+1 ,":")
for j in np.argsort(tfidf_matrix[i])[:-6:-1]:
print('{0: <15}'.format(feature_names[j]), tfidf_matrix[i, j])
print("\n")
输出:
Document 1 :
sentence 0.4387767423042408
first 0.4387767423042408
the 0.4387767423042408
is 0.4387767423042408
this 0.35872873824808923
Document 2 :
sentence 0.4387767423042408
second 0.4387767423042408
this 0.35872873824808923
one 0.4387767423042408
the 0.0
Document 3 :
sentence 0.4387767423042408
third 0.4387767423042408
this 0.35872873824808923
the 0.0
is 0.0
输出结果中,每个文本中的前五个关键词及其对应的TF-IDF值被列出。可以看到,这些关键词是这些文本的主要特征,可以用于文本分类、聚类和文本摘要等自然语言处理任务中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)