Dan*_*ion 2 python sorting mapreduce mrjob
有没有办法使用mrjob对reducer函数的输出进行排序?
我认为reducer函数的输入是按键排序的,我试图利用这个特性来使用另一个像下面这样的reducer对输出进行排序,我知道值有数值,我想计算每个键的数量并根据这个计数:
def mapper_1(self, key, line):
key = #extract key from the line
yield (key, 1)
def reducer_1(self, key, values):
yield key, sum(values)
def mapper_2(self, key, count):
yield ('%020d' % int(count), key)
def reducer_2(self, count, keys):
for key in keys:
yield key, int(count)
Run Code Online (Sandbox Code Playgroud)
但它的输出没有正确排序!我怀疑这种奇怪的行为是由于将ints操作为 asstring并尝试按照此链接所述对其进行格式化,但没有奏效!
重要说明:当我使用调试器查看订单的输出reducer_2顺序是正确的但作为输出打印的内容是别的东西!!!
重要说明 2:在另一台计算机上,相同数据上的相同程序返回按预期排序的输出!
您可以在第二个 reducer 中将值排序为整数,然后将它们转换为零填充表示:
import re
from mrjob.job import MRJob
from mrjob.step import MRStep
WORD_RE = re.compile(r"[\w']+")
class MRWordFrequencyCount(MRJob):
def steps(self):
return [
MRStep(
mapper=self.mapper_extract_words, combiner=self.combine_word_counts,
reducer=self.reducer_sum_word_counts
),
MRStep(
reducer=self.reduce_sort_counts
)
]
def mapper_extract_words(self, _, line):
for word in WORD_RE.findall(line):
yield word.lower(), 1
def combine_word_counts(self, word, counts):
yield word, sum(counts)
def reducer_sum_word_counts(self, key, values):
yield None, (sum(values), key)
def reduce_sort_counts(self, _, word_counts):
for count, key in sorted(word_counts, reverse=True):
yield ('%020d' % int(count), key)
Run Code Online (Sandbox Code Playgroud)
好吧,这是对内存中的输出进行排序,这可能是一个问题,具体取决于输入的大小。但是您希望对它进行排序,因此必须以某种方式对其进行排序。
| 归档时间: |
|
| 查看次数: |
4400 次 |
| 最近记录: |