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

相关推荐
羲云网络21 分钟前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗2 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn2 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_4045 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_5 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶5 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
卷无止境9 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿10 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户03321266636710 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿11 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu