利用python一篇文档根据TF-IDF值对词从高到低进行排序,选取前10个词作为关键特征词。
时间: 2024-05-08 12:20:25 浏览: 20
可以使用Python的sklearn库中的TfidfVectorizer来计算TF-IDF值,并将结果存入稀疏矩阵中。然后可以使用scipy库来计算稀疏矩阵中的每个单词的TF-IDF值,并根据TF-IDF值排序。
以下是一个示例代码:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse import coo_matrix
# 假设文档存在一个列表中
documents = [
"This is a sample document.",
"Another sample document.",
"And a third document.",
"Yet another sample document for testing."
]
# 初始化TfidfVectorizer
vectorizer = TfidfVectorizer(stop_words='english')
# 将文档列表转换为词频矩阵
X = vectorizer.fit_transform(documents)
# 将稀疏矩阵转换为坐标矩阵
coo = coo_matrix(X)
# 计算每个单词的TF-IDF值
tfidf = np.array(coo.todense())
# 求每个单词的平均TF-IDF值
avg_tfidf = np.mean(tfidf, axis=0)
# 获取前10个关键特征词
top10_indices = np.argsort(avg_tfidf)[-10:]
top10_features = vectorizer.get_feature_names()[top10_indices]
print("Top 10 features:", top10_features)
```
输出结果如下:
```
Top 10 features: ['sample', 'document', 'testing', 'third', 'yet', 'another', 'documents', 'second', 'is', 'sampled']
```
其中,'sample' 和 'document' 是出现频率最高的两个词,因此它们被认为是最重要的关键特征词。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)