sklearn 计算 tfidf 得到每个词分数

python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

# 语料库 可以换为其它同样形式的单词
corpus = [
    list(range(-5, 5)),
    list(range(-6,4)),
    list(range(12)),
    list(range(13))]

# corpus = [
#    ['Two', 'wrongs', 'don\'t', 'make', 'a', 'right', '.'],
#    ['The', 'pen', 'is', 'mightier', 'than', 'the', 'sword'],
#    ['Don\'t', 'put', 'all', 'your', 'eggs', 'in', 'one', 'basket', '.']]
    
def dummy_fun(doc):
    return doc
    
tfidf_vec = TfidfVectorizer(
    analyzer='word',
    tokenizer=dummy_fun,
    preprocessor=dummy_fun,
    token_pattern=None)  

# 使用 fit_transform() 得到 TF-IDF 矩阵。此为 scipy 稀疏矩阵
tfidf_matrix = tfidf_vec.fit_transform(corpus)
# print(tfidf_matrix)

# 使用 get_feature_names() 得到不重复的单词
print(tfidf_vec.get_feature_names_out())

# 得到每个单词对应的 ID
print(tfidf_vec.vocabulary_)
python 复制代码
# 得到 corpus 中每个词得分
for i in range(len(corpus)):
    column_indexes = [tfidf_vec.vocabulary_[key] for key in corpus[i]]
    tf_idf = tfidf_matrix[i, column_indexes].toarray()[0]
    print(tf_idf)

参考:
Applying scikit-learn TfidfVectorizer on tokenized text
sklearn.feature_extraction.text.TfidfVectorizer

相关推荐
在星空下几秒前
Fastapi-Vue3-Admin
前端·python·fastapi
cxyll12348 分钟前
从接口自动化测试框架设计到开发(三)主流程封装、返回数据写入excel
前端·python·excel
Kyln.Wu12 分钟前
【python实用小脚本-190】Python一键删除PDF任意页:输入页码秒出干净文件——再也不用在线裁剪排队
服务器·python·pdf
九章云极AladdinEdu1 小时前
Scikit-learn通关秘籍:从鸢尾花分类到房价预测
人工智能·python·机器学习·分类·scikit-learn·gpu算力
抠头专注python环境配置2 小时前
Pytorch GPU版本安装保姆级教程
pytorch·python·深度学习·conda
小磊哥er2 小时前
【办公自动化】如何使用Python自动化处理PDF文档?
python
大模型真好玩2 小时前
DeepSeek更新!速览DeepSeek V3.1新特性
人工智能·python·mcp
CF14年老兵2 小时前
Python参数传递:从混沌到明晰的魔法之旅
后端·python·trae
CF14年老兵2 小时前
Python变量与内存:每个新手都需要的灵魂拷问
前端·python·trae
喂完待续11 小时前
【Tech Arch】Spark为何成为大数据引擎之王
大数据·hadoop·python·数据分析·spark·apache·mapreduce