【问题标题】:How can i change this reducer code to find the longest words (and the length) rather than it finding the frequency of the words?我如何更改此减速器代码以查找最长的单词(和长度)而不是查找单词的频率?
【发布时间】:2021-11-04 11:13:08
【问题描述】:

REDUCER CODE 此代码从文本文件中查找单词的频率,我想知道如何更改它以查找文本文件中最长的单词并将它们打印出来,例如。 "最长的单词有13个字符。结果包括:"

import sys
results = {}
for line in sys.stdin:
    word, frequency = line.strip().split('\t', 1)
    results[word]=results.get(word,0) + int(frequency)
    words = list(results.keys())
    words.sort()
    for word in words:
        print(word,results[word])

映射器代码

import sys
for line in sys.stdin:
    for word in line.strip().split():
        print (word , "1")

【问题讨论】:

  • 只是循环遍历所有单词,并将最长的单词保留在变量中?
  • 映射器没有理由输出它看到的每一个单词。为什么不让映射器只输出一条记录——它看到的最长的词——然后让一个 reducer 从这些记录中挑选最长的词。您希望所有 map 输出记录都转到同一个 reducer,因此您需要考虑您的关键设计。

标签: python mapreduce


【解决方案1】:

如果你不想保留所有单词,那么你可以这样做:

longest = set()
max_length = 0
for line in sys.stdin:
    for word in line.strip().split():
        length = len(word)
        if length > max_length:
            max_length = length
            longest = {word}
        elif length == max_length:
            longest.add(word)

print(longest)

如果您想保留它们,按长度分组,您可以使用defaultdict:

from collections import defaultdict

words_length = defaultdict(set)
for line in sys.stdin:
    for word in line.strip().split():
        words_length[len(word)].add(word)

print(words_length[max(words_length)])

【讨论】:

  • 在 MapReduce 作业中将每条记录存储在内存中并不是一个好主意。只记录当前最长的单词。
  • @BenWatson 同意,如果这正是操作人员真正想要的。但我不确定,问题的第一部分听起来不同。
  • @timus - 你是对的。我正在尝试完成一个已设置的练习,我们得到了显示的映射器和减速器,并且必须纠正常规的 python 代码才能得到答案 - 我做到了,文件中有两个单词都是 13 个字符长度 - 所以它们都需要输出。然后我必须修改映射器和减速器以获得相同的输出。因此,从 mu 的理解来看,映射器将所有单词都提供给减速器,然后减速器将选择文件中最长的单词并输出它们。我想你的回答会让我得到我需要的——谢谢
【解决方案2】:

以我的建议为基础(循环单词,在变量中保持最长):

longest = ""

for line in something:
    for word in line.lower().split():
        if len(word.strip()) > len(longest):
            longest = word.strip()

print("Longest word is:", longest, "with the length of:", len(longest))

【讨论】:

  • 请记住,当通过 Hadoop-Streaming Mapreduce 函数运行时,会一次读取多个文件部分,每个部分都有自己的最长单词...因此,您需要一个 reducer 函数来查找其中最长的
  • 随意编辑答案,但 OP 在这方面没有提供太多信息,所以在这种情况下我真的帮不上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 2013-11-01
  • 2014-09-26
  • 1970-01-01
相关资源
最近更新 更多