【问题标题】:How to get the longest word in the MRjob如何在 MRjob 中获得最长的单词
【发布时间】:2022-07-03 07:44:41
【问题描述】:

我正在尝试通过字母 a->z 在文本文件中找到最长的单词。我是 Python 新手,刚刚进入 Mrjob 这是我的代码

from mrjob.job import MRJob
import re

WORD_RE = re.compile(r"[\w']+")

class MRWordFreqCount(MRJob):

    def mapper(self, _, line):
        for word in WORD_RE.findall(line):
            yield word[0].lower(), 1

    def combiner(self, word, counts):
        yield word, sum(counts)

    def reducer(self, _, word_count_pairs):
        longest_word = ''
        for word in word_count_pairs:
            if len(word) > len (longest_word):
                longest_word = word
        yield max(longest_word)

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

输出应该是这样的,但我卡在这里

"r" ["recommendations", "representations"]

"s" ["superciliousness"]

【问题讨论】:

    标签: python mapreduce mrjob


    【解决方案1】:

    您的映射器当前仅输出每个单词的第一个字符。

    然后您的组合器会计算以该字母开头的单词有多少...这无助于找到整个单词的最大值。


    部分问题 - max() 仅适用于数字仅返回一个值,因此无法帮助找到长度相同的最长单词

    如果您不关心前导字母,那么 mapreduce 并不是真正有益的,因为您需要将所有单词强制到一个 reducer 中——例如下面的例子。此外,对于非常大的文件,不推荐使用这种方法

    def mapper(self, _, line):
        for word in WORD_RE.findall(line):
            yield None, word
    
    def reducer(self, _, words):
        lst = list(words)  # copy out iterator to in memory list 
        lens = max(len(w) for w in words)
        max_words = [w for w in words if len(w) == max_words] 
        yield None, max_words 
    

    上面的替代策略是找到每个字母的最大长度单词,然后,如果你想找到整体最大值,将输出传递给辅助 mapreduce 作业

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 2011-02-01
      • 2019-04-28
      • 2016-10-30
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      相关资源
      最近更新 更多