Python中如何使用MapReduce统计一个单词序列在一个文件中出现的次数?

How to count the number of times a word sequence appears in a file, using MapReduce in Python?

考虑一个包含由空格分隔的单词的文件;在 Python 中编写一个 MapReduce 程序, 它计算每个 3 字序列在文件中出现的次数。

例如,考虑以下文件:

one two three seven one two three
three seven one
seven one two

该文件中每个 3 个单词序列出现的次数是:

"three seven one" 2
"four seven one two" 1
"one two three" 2
"seven one two" 2
"two three seven" 1

代码格式:

from mrjob.job import MRJob


class MR3Nums(MRJob):
    
    def mapper(self,_, line):
        pass

    def reducer(self,key, values):
        pass
    

if __name__ == "__main__":
    MR3Nums.run()

映射器应用于每一行,并且应该对每个 3 字序列进行计数,即产生 3 字序列以及计数 1。

reducer 使用 keyvalues 调用,其中 key 是一个 3 字序列,values 是一个计数列表(这将是一个1s 列表)。 reducer 可以简单地 return 一个 3 字序列和出现总数的元组,后者通过求和获得。

class MR3Nums(MRJob):
    
    def mapper(self, _, line):
        sequence_length = 3
        words = line.strip().split()
        for i in range(len(words) - sequence_length + 1):
            yield " ".join(words[i:(i+sequence_length)]), 1

    def reducer(self, key, values):
        yield key, sum(values)