使用python实现文本特征向量化
时间: 2024-01-01 16:06:44 浏览: 42
在Python中,我们可以使用scikit-learn库中的CountVectorizer和TfidfVectorizer来实现文本特征向量化。
CountVectorizer将文本转换为词频矩阵,每一行表示一个文本样本,每一列表示一个单词,单元格中的数字表示该单词在该文本中出现的次数。示例代码如下:
```python
from sklearn.feature_extraction.text import CountVectorizer
# 定义文本样本
corpus = [
'This is the first document.',
'This is the second document.',
'And this is the third one.',
'Is this the first document?',
]
# 创建CountVectorizer对象
vectorizer = CountVectorizer()
# 对文本进行向量化
X = vectorizer.fit_transform(corpus)
# 打印词汇表
print(vectorizer.get_feature_names())
# 打印向量化结果
print(X.toarray())
```
输出结果如下:
```
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
[[0 1 1 1 0 0 1 0 1]
[0 1 0 1 0 1 1 0 1]
[1 0 0 1 1 0 1 1 1]
[0 1 1 1 0 0 1 0 1]]
```
TfidfVectorizer将文本转换为TF-IDF权重矩阵,每一行表示一个文本样本,每一列表示一个单词,单元格中的数字表示该单词在该文本中的TF-IDF权重。示例代码如下:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
# 定义文本样本
corpus = [
'This is the first document.',
'This is the second document.',
'And this is the third one.',
'Is this the first document?',
]
# 创建TfidfVectorizer对象
vectorizer = TfidfVectorizer()
# 对文本进行向量化
X = vectorizer.fit_transform(corpus)
# 打印词汇表
print(vectorizer.get_feature_names())
# 打印向量化结果
print(X.toarray())
```
输出结果如下:
```
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
[[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]
[0. 0.46979139 0. 0.38408524 0. 0.58028582
0.38408524 0. 0.38408524]
[0.51785612 0. 0. 0.34261901 0.51785612 0.
0.34261901 0.51785612 0.34261901]
[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)