首页 > 解决方案 > Gensim-python:有没有一种简单的方法来获取给定标记在所有文档中出现的次数?

问题描述

我的gensim模型是这样的:

class MyCorpus(object):
    parametersList = []
    def __init__(self,dictionary):
       self.dictionary=dictionary
    def __iter__(self):
        #for line in open('mycorpus.txt'):
        for line in texts:
            # assume there's one document per line, tokens separated by whitespace
            yield self.dictionary.doc2bow(line[0].lower().split())




if __name__=="__main__":
    texts=[['human human interface computer'],
             ['survey user user computer system system system response time'],
             ['eps user interface system'],
             ['system human system eps'],
             ['user response time'],
             ['trees'],
             ['graph trees'],
             ['graph minors trees'],
             ['graph minors minors survey survey survey']]


    dictionary = corpora.Dictionary(line[0].lower().split() for line in texts)

    corpus= MyCorpus(dictionary)

自动评估每个文档中每个标记的频率。

我还可以定义 tf-idf 模型并访问每个文档中每个标记的 tf-idf 统计信息。

model = TfidfModel(corpus)

但是,我不知道如何计算(记忆友好的)给定单词出现的文档数量。我怎样才能做到这一点?[当然...我可以使用 tf-idf 和文档频率的值来评估它...但是,我想直接从一些计数过程中评估它]

例如,对于第一个文件,我想得到类似的东西

[('human',2), ('interface',2), ('computer',2)]

因为上面的每个标记在每个文档中出现两次。

对于第二个。

[('survey',2), ('user',3), ('computer',2),('system',3), ('response',2),('time',2)]

标签: nlpgensim

解决方案


这个怎么样?

from collections import Counter

documents = [...]
count_dict = [word_count(document) for filename in documents]

total = sum(count_dict, Counter())

我假设您的所有字符串都是不同的文档/文件。您可以进行相关更改。另外,对代码进行了更改。


推荐阅读