繁体   English   中英

如何计算一个单词序列在文件中出现的次数,使用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-word 序列,即产生 3-word 序列以及计数为 1。

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM