【问题标题】:Need to count the number of documents in a particular directory using python - MapReduce需要使用python计算特定目录中的文档数 - MapReduce
【发布时间】:2020-01-14 04:28:58
【问题描述】:

请找到我正在使用的以下程序。它正在编译但没有给出任何输出。请求帮助解决错误。

import gzip
import warc
import os
from mrjob.job import MRJob


class DocumentCounter(MRJob):
    def mapper(self, _, line):
        entries = os.listdir("C://Users//HP//WARCDataset")
        for entry in entries:
            yield 1,1

    def reducer(self, key, values):

        yield key, sum(values)

if __name__ == '__main__':
     DocumentCounter.run() 

IDE 和输出窗口的截图。即使程序运行成功,也不显示结果。

【问题讨论】:

  • 我不确定你的代码有什么问题,但你真的需要一个类来计算文档数量吗?您可以通过以下方式轻松完成:b = len([x for x in os.listdir(folder) if x.endswith(file_extension)])
  • @pavel:就像你说的,用 Python 内部函数可以做到,但她想使用 MapReduce 算法,所以她需要一个类。
  • @NachiketDeo:您的代码似乎是正确的。你能展示你如何从终端运行代码吗?
  • @codrelphi 感谢您的评论。我正在通过按“运行”按钮在 Enthought-Canopy IDE 上的本地计算机上运行代码。我没有使用任何命令来运行文件。请让我知道是否有任何可以用来运行的命令。
  • @NachiketDeo 您的输出应位于 job output is instreaming final output from 行旁边列出的文件夹之一中。您可以检查这些文件夹。

标签: python python-3.x mapreduce mrjob


【解决方案1】:
class DocumentCounter(MRJob):
   
    def mapper_raw(self,_,line):
        for fname in os.listdir(WARC_PATH):
            yield "total_documents",1

    def combiner(self, key, values):
    """
    Sums up count for each mapper.
    """
        yield key, sum(values)
                

    def reducer(self, key, values):
    ##TOTAL_DOUCMENTS = sum(values)
        NumberofDocuments = sum(values)     
        yield key, NumberofDocuments


       
    if __name__ == '__main__':
         DocumentCounter.run()

上面的代码使用 os.listdir 函数遍历给定路径下的所有文件

【讨论】:

  • 这是您的问题的解决方案还是应该是问题的一部分?在我看来是后者
  • 这是解决问题的方法。当给定目录正确路径时,此代码可提供该特定目录中文档数量的答案
猜你喜欢
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 2019-01-16
  • 1970-01-01
  • 2012-08-04
相关资源
最近更新 更多