首页 > 解决方案 > 从一组文档中,如何在 python 中为 Mapreduce 计算单词、文档数和计数

问题描述

我有两个文档,我需要计算两个文档中的单词数,以及每个单词的文档名称。doc1.txt = "我有一个苹果", doc2.txt = "我住在公寓里"。现在我想做 MapReduce,输出看起来像这样:((word, document name),count)。示例:((apple, doc1.txt),1)

#!/usr/bin/env python

import sys import glob #from string import punctuation #--- 从 stdin 获取所有行 --- for line in sys. stdin: #--- 删除前导和尾随空格--- #line=line.translate(None, punctuation).strip('\t') line = line.strip()

#--- split the line into words ---
words = line.split()
doc_name = glob.glob("*.txt")

for doc in doc_name:
    print(doc)
    if doc[] == '':
        
    for word in words:
        
        #word = word.rstrip()
        key = word+ ',' +doc 
        #print '%s\t%s' % (key, "1")

此代码每次都会打印每个文档中的所有单词,但是对于两个文档,它们会在每个单词中分配每个文档名称,如下所示: (apple, doc1.txt),1 (apple, doc2.txt),1

标签: pythonmapreduce

解决方案


推荐阅读