python - Mapreduce在Python中的词频

标签 python hadoop mapreduce mrjob

我希望我的python程序输出前十个最常用的单词及其相关单词计数的列表。我必须使用mrjob-mapreduce创建此程序。我编写了一个程序,该程序可以找到单词的出现频率,并从最大到最小输出它们。但是我不确定如何仅输出前十个最常用的单词。我当时想也许可以将其放在列表中,然后使用第二个map reducer进行排序,但是我不确定如何使用mapreduce做到这一点。我使用mapreduce和python进行了新编程。
有人可以给我任何建议吗?

from mrjob.job import MRJob
from mrjob.step import MRStep
import re

# Word frequency from book sorted by frequency
# File: book.txt  

# regular expression used to identify word
WORD_REGEXP = re.compile(r"[\w']+")

class MRWordFrequencyCount(MRJob):

    def steps(self):
        # 2 steps
        return [
            MRStep(mapper=self.mapper_get_words,
                   reducer=self.reducer_count_words),
            MRStep(mapper=self.mapper_make_counts_key,
                   reducer=self.reducer_output_words)
        ]

    # Step 1
    def mapper_get_words(self, _, line):
        words = WORD_REGEXP.findall(line)
        for w in words:
            yield w.lower(), 1

    def reducer_count_words(self, word, values):
        yield word, sum(values)

    # Step 2
    def mapper_make_counts_key(self, word, count):
        # sort by values
        yield '%04d' % int(count), word

    def reducer_output_words(self, count, words):
        # First Column is the count
        # Second Column is the word
        for word in words:
            yield count, word


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

最佳答案

您的结果是键,值的无序集合。一种解决方案是转换为元组列表,因为您仍然可以维护单词和计数的数据关联,并同时引入索引进行排序。
https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts
然后,您可以分割最常见的前10个

关于python - Mapreduce在Python中的词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900034/

相关文章:

python - 将 sphinx autodoc 用于 fabfile

python - 有没有办法通过ffmpeg中的启用功能在最后3秒在视频中添加drawtext过滤器

date - 如何从时间戳中分离日期和时间并将其存储在Hive的另一个表中

hadoop - PIG 拉丁语 : Output Path based on Field Value

scala - 使用 apache spark 自动运行任务

Hadoop Mapreduce MultipleOutputs 输出控制台

python - Hadoop YARN 与 mapreduce

python - Keras:如何在顺序模型中获取图层形状

python - 将 pandas 对象提取到列表列表中并提取唯一值

java - Hadoop错误:java.io.IOException:映射中 key 的类型不匹配:预期的org.apache.hadoop.io.Text,收到org.apache.hadoop.io.LongWritable