【发布时间】:2017-10-23 23:39:00
【问题描述】:
我希望我的 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()
【问题讨论】:
标签: python hadoop mapreduce mrjob