Skip to main content
 首页 » 编程设计

python之如何计算字典列表的 tf-idf

2024年10月25日14duanxz

我有一个文本列表,其中每个文本都存储为字典,其 id 作为键,文本数据作为其值。我如何计算 tf-idf对于这个数据。例如:

{1: 'This is cat', 2: 'Is this the first document?', 3: 'And the third one.'} 

请您参考如下方法:

首先通过以下方式将您的字典转换为字符串列表:

    X_all = list(d.values()) 

将 tfIDFVectoriser 函数构建为:

    from sklearn.feature_extraction.text import TfidfVectorizer 
 
    tfv = TfidfVectorizer(min_df=3,  max_features=None, 
    strip_accents='unicode', analyzer='word',token_pattern=r'\w{1,}', 
    ngram_range=(1,2), use_idf=1,smooth_idf=1,sublinear_tf=1, 
    stop_words = 'english') 

然后您可以将模型构建为:

    X_all = tfv.transform(X_all) 

其中 X_all 是文本文档列表。