【问题标题】:Remove tokens by document frequency按文档频率删除标记
【发布时间】:2017-09-03 08:19:11
【问题描述】:

我有这个代码:

# Remove words that appear less than X (e.g. 2) time(s)
from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
    for token in text:
        frequency[token] += 1

texts = [[token for token in text if frequency[token] > 2] for text in texts]

现在这是否会过滤掉所有词频(所有文本中的总出现次数)低于 2 或文档频率(其中出现一次或多次的文本总数)低于 2 的标记?

编辑:

# Get term frequencies (how many times a term occurs no matter what)

from collections import Counter
termfrequency = Counter()
for text in texts:
    for token in text:
        termfrequency[token] +=1

texts = [[token for token in text if termfrequency[token] > 2] for text in texts]

# Get document frequencies (in how many documents a term exists > 0 times)

from collections import Counter
documentfrequency = Counter()
for text in texts:
    documentfrequency.update(set(text))

texts = [[token for token in text if documentfrequency[token] > 2] for text in texts]

【问题讨论】:

  • 怎么想,为什么?请告诉我们,我们会让您发现错误(如果有的话:))。
  • 嗯,这取决于defaultdict 的实际作用。据我了解,我的代码在这里设置了一个字典,然后由 for 循环填充。 for 循环遍历所有 texts 并为文本中的每个标记创建一个 defaultdict。我认为它因此计算 TF,但我希望它计算 DF。
  • 看看 nltk,它是用于对大型文档集合进行自然语言处理的 python 库。它包括信息检索功能,如 tf 和 idf。
  • @textnet:你的推理完全正确。如果要为每个文档计算单独的频率,则需要在文档之间清除 frequency(例如,通过创建新的 defaultdict)。
  • @NPE 并不是每个文档的单独频率,而是一个单词在整个集合中出现的文档数量,无论它在任何特定文档中出现多少次。

标签: python collections


【解决方案1】:

[我想计算]一个单词在整个集合中出现的文档数,无论它在任何特定文档中出现多少次。

这是一种方法:

from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
    for token in set(text):
               # ^^^ set() only keeps one occurrence of each word
        frequency[token] += 1

texts = [[token for token in text if frequency[token] > 2] for text in texts]

在这里使用defaultdict 没有任何问题。然而,值得注意的是collections 模块有一个更适合手头任务的类。它被称为Counter

from collections import Counter
frequency = Counter()
for text in texts:
    frequency.update(set(text))
texts = [[token for token in text if frequency[token] > 2] for text in texts]

【讨论】:

  • 您的代码看起来不错:它设置了字典(就像一个计数器)。然后遍历所有文本,仅查看唯一单词并添加到字典和/或每次出现单词时增加计数器。 Counter 会以任何方式简化它吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
相关资源
最近更新 更多