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

How to calculate tf-idf for a list of dict?

我有一个文本列表,其中每个文本都存储为字典,其 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 是文本文档列表。