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

相关推荐
weixin_5142218541 分钟前
FDTD与matlab、python耦合
python·学习·matlab·fdtd
F_D_Z6 小时前
数据集相关类代码回顾理解 | StratifiedShuffleSplit\transforms.ToTensor\Counter
python·torchvision·transforms
tao3556677 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
小宁爱Python7 小时前
从零搭建 RAG 智能问答系统1:基于 LlamaIndex 与 Chainlit实现最简单的聊天助手
人工智能·后端·python
湖南人爱科技有限公司7 小时前
RaPhp和Python某音最新bd-ticket-guard-client-data加密算法解析(视频评论)
android·python·php·音视频·爬山算法·raphp
eqwaak09 小时前
数据预处理与可视化流水线:Pandas Profiling + Altair 实战指南
开发语言·python·信息可视化·数据挖掘·数据分析·pandas
心态特好10 小时前
详解WebSocket及其妙用
java·python·websocket·网络协议
dlraba80210 小时前
用 Python+OpenCV 实现实时文档扫描:从摄像头捕捉到透视矫正全流程
开发语言·python·opencv
小熊出擊10 小时前
【pytest】fixture 内省(Introspection)测试上下文
python·单元测试·pytest
njsgcs11 小时前
sse mcp flask 开放mcp服务到内网
后端·python·flask·sse·mcp