【问题标题】:How to calculate the number of documents a term occurs in using python?如何计算一个术语在使用python时出现的文档数?
【发布时间】:2020-02-14 12:10:12
【问题描述】:

我正在尝试计算 TF-IDF 矢量化的 IDF 值。我正在尝试计算包含该词汇的每个唯一单词的文档数。

这是语料库:

corpus = ['这是第一个文档', '这个文件是第二个文件', '这是第三个', '这是第一个文件吗']

我的代码:

...

IDF 值:

for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c) 

...

我得到的输出: 和 0 文档 0 第一个 1 是 3 一个 3 第二个 3 4 第三个 4 这 5 和 0 文件 1 第一个 1 是 3 一个 3 第二个 3 4 第三个 4 这 5 和 1 文件 1 第一个 1 是 3 一个 3 第二个 3 4 第三个 4 这 5 和 0 文档 0 第一个 1 是 3 一个 3 第二个 3 4 第三个 4 这5

我需要的输出: 这 4 是 4 4 前 2 文件 3 第二个 1 和 1 第三个 1 一个 1

【问题讨论】:

    标签: python tf-idf


    【解决方案1】:

    我假设n 包含您的词汇表。然后你可以这样做:

    wordsets = [ frozenset(document.split(' ')) for document in corpus ]
    results = []
    for word in n:
        count = sum( 1 for s in wordsets if word in s )
        results.append((count, word))
    for count, word in sorted(results, reverse=True):
        print(word, count)
    

    【讨论】:

    • 这正是我正在尝试的。非常感谢!
    【解决方案2】:

    你可以这样做。但是,您要计算的不是 IDF。这只是所有文档中特定单词的频率。

     for i in range(0,len(corpus)):
       words=corpus[i].split(' ')
       for word in words:
         if word in freq:
           freq[word] = freq[word] + 1
         else:
           freq[word] = 1
     print(freq)
    

    【讨论】:

      【解决方案3】:

      这非常适合 collections 包中的 Counter

      from collections import Counter
      
      words = ' '.join(corpus)
      output = Counter(words.split()).most_common()
      

      【讨论】:

      • 一个非常好的解决方案,解决一个非常不同的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      相关资源
      最近更新 更多