假设您的映射器正在获取一个完整的句子,您正在尝试查找频率并且您正在使用 Java API,您可以通过 context.write(...) 函数从映射器输出两个键:
映射器的java语法:public void map(LongWritable key, Text value, Context context)
- 密钥:
<lineNo_Letter>;值:c_m
- 键:
<lineNo_Letter>;值:t_n
在哪里
lineNo = same as key to the mapper (the first parameter to the above function)
letter = your desired letter
m = <total number of letters in the line (the 2nd parameter to the above function) input to the mapper>
n = <number of occurrence of letter in the line (the 2nd parameter to the above function) mapper input line>
c_ 和 a_ 只是识别计数类型的前缀。 c代表字母的出现;而t代表出现的总数。
基本上,我们在这里利用的概念是,您可以从 mapper/reducer 中写入任意数量的键值。
现在减速器会得到类似的东西
键:<lineNo_letter> 值:ListOf[c_m, t_n]
现在,只需在列表上进行迭代,使用分隔符 _ 和标识符前缀(t 和 c)将其拆分;您在减速器中有所需的值。即
Total number of letter in the sentence = m
Total number of occurrence of the letter = n
编辑:添加伪逻辑
以您的示例为例,假设映射器函数public void map(LongWritable key, Text value, Context context) 的输入行是
LongWritable key = 1
Text value = howareyou
映射器的输出应该是:
-- Output length of the Text Value against each letter
context.write("1_h", "t_9");
context.write("1_o", "t_9");
context.write("1_w", "t_9");
context.write("1_a", "t_9");
context.write("1_r", "t_9");
context.write("1_e", "t_9");
context.write("1_y", "t_9");
context.write("1_u", "t_9");
请注意,上述输出是映射器中句子的每个字母一次。这就是为什么字母o 只输出一次(即使它在输入中出现两次)。
映射器代码的更多输出将是
-- Output individual letter count in the input text as
context.write("1_h", "c_1");
context.write("1_o", "c_2");
context.write("1_w", "c_1");
context.write("1_a", "c_1");
context.write("1_r", "c_1");
context.write("1_e", "c_1");
context.write("1_y", "c_1");
context.write("1_u", "c_1");
同样,您可以看到字母 o 的值等于 c_2,因为它在句子中出现了两次。
现在将生成 8 个 reducer,每个都将获得以下键值对之一:
key: "1_h" value: ListOf["t_9", "c_1"]
key: "1_o" value: ListOf["t_9", "c_2"]
key: "1_w" value: ListOf["t_9", "c_1"]
key: "1_a" value: ListOf["t_9", "c_1"]
key: "1_r" value: ListOf["t_9", "c_1"]
key: "1_e" value: ListOf["t_9", "c_1"]
key: "1_y" value: ListOf["t_9", "c_1"]
key: "1_u" value: ListOf["t_9", "c_1"]
现在在每个 reducer 中,拆分 key 以获得行号和字母。
遍历值列表以提取出现的总数和字母。
第 1 行中字母 h 的频率 = Integer.parseInt("c_1".split("_")[1])/Integer.parseInt("t_9".split("_")[1])
这是一个供你实现的伪逻辑。