Python中的文档频率

2024-10-01 15:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算一个特定单词出现的文档数。例如,100个文档中有67个文档中出现了“Dog”一词。在

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

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

示例:

  • 文件一:狗出现250次
  • 文件二:狗出现1000次
  • 文件三:狗出现一次
  • 文件四:狗出现了0次
  • 文件五:狗出现了2次

所以答案必须是4

我有我自己的算法,但我相信有一个有效的方法来做到这一点。我使用的是python3.4和NLTK库。我需要帮助。谢谢你们!在

这是我的密码

# 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)

Tags: 文件in文档forif计数frequencydog
2条回答

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

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})

这可以在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

相关问题 更多 >

    热门问题