我需要一个特定单词出现的文档的数量
示例:
data = ["This is my pen","That is his pen","This is not my pen"]
期望输出:
{'This':2,'is': 3,'my': 2,'pen':3}
{'That':1,'is': 3,'his': 1,'pen':3}
{'This':2,'is': 3,'not': 1,'my': 2,'pen':3}
for sent in documents:
for word in sent.split():
if word in sent:
windoc=dict(Counter(sent.split()))
print(windoc)
考虑到每个文件的字数不得超过一次:
您需要先对单词进行重复数据消除(请参见上面的
deduped
)。我制作了一个重复数据消除生成器,以避免使用中间列表集,但这将为每个文档生成一个中间词集。你知道吗或者,您可以实现自己的计数器。一般来说,实现自己的计数器不是一个好主意,但如果内存消耗非常重要,并且您希望避免在
deduped
生成器上迭代时创建的中间集,则可能需要实现。你知道吗不管怎样,时间和内存复杂度都是线性的。你知道吗
输出:
您可以根据所有可用的句子构造一个字典来保存
words frequency
。然后构造所需的输出。下面是一个工作示例:给定输入文件:
构建词频词典:
然后构造所需的输出:
所以,总的来说,代码是这样的:
输出:
相关问题 更多 >
编程相关推荐