【发布时间】: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