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

相关推荐
Csvn2 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89182 天前
Python主流框架全解析
开发语言·python
sg_knight2 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财2 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4082 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533992 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz2 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据2 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby2 天前
springboot读取配置文件
后端·python·flask
阿Y加油吧2 天前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python