当前位置:首页 > 行业动态 > 正文

python 如何计算tf

在Python中,我们可以使用sklearn库中的TfidfVectorizer来计算TF(词频),以下是详细的步骤:

1、导入所需的库。

python 如何计算tf  第1张

2、创建一个文本列表。

3、使用TfidfVectorizer计算TF。

python 如何计算tf  第2张

4、打印结果。

代码如下:

python 如何计算tf  第3张

导入所需的库
from sklearn.feature_extraction.text import TfidfVectorizer
创建一个文本列表
documents = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?',
]
使用TfidfVectorizer计算TF
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)
打印结果
print("Feature Names: ", vectorizer.get_feature_names())
print("TFIDF Matrix: ")
print(X.toarray())

在这个例子中,我们首先创建了一个包含四个文档的列表,我们使用TfidfVectorizer来计算每个单词在每个文档中的TFIDF值,我们打印出所有的特征名(即所有的单词)和TFIDF矩阵。

0