在列表字典上使用 TfidfVectorizer

Using TfidfVectorizer on a Dictionary of Lists

我有一个大型语料库存储为 25 个列表的字典,我想用 SKLearn 的 TfidfVectorizer 进行分析。每个列表包含许多字符串。现在,我既关心整个语料库中的总体词频 (tf),也关心 25 个字符串的每个列表中最独特的词 (idf)。问题是,我还没有找到将这种对象传递给 TfidfVectorizer 的方法。传递 dict 只是向量化键,传递值会产生一个 AttributeError: 'list' object has no attribute 'lower' (我猜它需要一个字符串。)

提前致谢。

更新:现在包括我的预处理步骤,它使用了 dict 区域,ID 对称为 buckets

for area in buckets:
    area_docs = []
    for value in buckets[area]:   
        if 'filename_%s.txt' % value in os.listdir(directory):
            fin = open(directory+'/filename_%s.txt' % value, 'r').read() 
            area_docs.append(fin)
            buckets[area] = area_docs



corpus = buckets.values()
vectorizer = TfidfVectorizer(min_df=1, stop_words='english')
X = vectorizer.fit_transform(corpus)
idf = vectorizer.idf_
d = dict(zip(vectorizer.get_feature_names(), idf))
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
sorted_d[:50]

TfidfVectorizer 想要一个字符串列表,其中每个字符串都是一个文档。您的 area_docs 变量已经是一个字符串列表,因此当您调用 buckets.values() 时,您会得到一个字符串列表列表,这对于 TfidfVectorizer 来说维度太多了。您需要展平该列表。下面的代码在 Python3 中,只更改了一行并添加了另一行:

for area in buckets:
    area_docs = []
    for value in buckets[area]:   
        if 'filename_%s.txt' % value in os.listdir(directory):
            fin = open(directory+'/filename_%s.txt' % value, 'r').read() 
            area_docs.append(fin)
            buckets[area] = area_docs

corpus = list(buckets.values()) # Get your list of lists of strings
corpus = sum(corpus, []) # Good trick for flattening 2D lists to 1D
vectorizer = TfidfVectorizer(min_df=1, stop_words='english')
X = vectorizer.fit_transform(corpus)
idf = vectorizer.idf_
d = dict(zip(vectorizer.get_feature_names(), idf))
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
sorted_d[:50]

应该可以!