【问题标题】:Document Frequency in PythonPython 中的文档频率
【发布时间】:2019-09-19 05:17:59
【问题描述】:

我想计算一个特定单词出现了多少文档。例如,“狗”这个词出现在 100 个文档中的 67 个文档中。

1 个文档相当于 1 个文件。

因此,“狗”这个词的出现频率不必计算在内。例如在文档 1 中,“Dog”出现了 250 次,但它只会被视为一次,因为我的目标是计算文档而不是“Dog”一词在特定文档中出现的次数。

例子:

  • 文档 1:狗出现了 250 次
  • 文档 2:狗出现了 1000 次
  • 文档 3:狗出现了 1 次
  • 文档 4:狗出现 0 次
  • 文档 5:狗出现了 2 次​​li>

所以答案必须是 4

我有自己的算法,但我相信有一种有效的方法可以做到这一点。我正在使用带有 NLTK 库的 Python 3.4。我需要帮助。谢谢你们!

这是我的代码

# DOCUMENT FREQUENCY
for eachadd in wordwithsource:
    for eachaddress in wordwithsource:
        if eachaddress == eachadd:
            if eachaddress not in copyadd:
                countofdocs=0
                copyadd.append(eachaddress)
                countofdocs = countofdocs+1
                addmanipulation.append(eachaddress[0])

for everyx in addmanipulation:
    documentfrequency = addmanipulation.count(everyx)
    if everyx not in otherfilter:
        otherfilter.append(everyx)
        documentfrequencylist.append([everyx,documentfrequency])

#COMPARE WORDS INTO DOC FREQUENCY 
for everywords in tempwords:
    for everydocfreq in documentfrequencylist:
        if everywords.find(everydocfreq[0]) !=-1:
            docfreqofficial.append(everydocfreq[1])

for everydocfrequency in docfreqofficial:
    docfrequency=(math.log10(numberofdocs/everydocfrequency))
    docfreqanswer.append(docfrequency)

【问题讨论】:

    标签: python nltk document frequency


    【解决方案1】:

    这可以在 gensim 中完成。

    from gensim import corpora
    
    dictionary = corpora.Dictionary(doc for doc in corpus)
    dictionary.dfs
    

    doc 是标记列表,corpus 是文档列表。 Dictionary 实例还存储整体词频 (cfs)。

    https://radimrehurek.com/gensim/corpora/dictionary.html

    【讨论】:

      【解决方案2】:

      您可以为每个文档存储一个频率字典,并为单词的文档频率使用另一个全局字典。为了简单起见,我使用了 Counter。

      from collections import Counter
      
      #using a list to simulate document store which stores documents
      documents = ['This is document %d' % i for i in range(5)]
      
      #calculate words frequencies per document
      word_frequencies = [Counter(document.split()) for document in documents]
      
      #calculate document frequency
      document_frequencies = Counter()
      map(document_frequencies.update, (word_frequency.keys() for word_frequency in word_frequencies))
      
      print(document_frequencies)
      
      >>>...Counter({'This': 5, 'is': 5, 'document': 5, '1': 1, '0': 1, '3': 1, '2': 1, '4': 1})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-21
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 2011-05-21
        • 2015-12-31
        • 2016-01-23
        • 2021-02-20
        相关资源
        最近更新 更多