gpt4 book ai didi

java - 每个文件计数的 WordCount 示例

转载 作者:行者123 更新时间:2023-12-02 21:34:55 27 4
gpt4 key购买 nike

我在获取每个文件的单词出现总数的分割时遇到了问题。
例如,我有四个文本文件(t1、t2、t3、t4)。单词 w1 在文件 t2 中出现了两次,在 t4 中出现了一次,总共出现了 3 次。
我想在输出文件中写入相同的信息。
我得到了每个文件中的总字数,但无法得到我想要的结果。

这是我的 map 课。

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
//line added
import org.apache.hadoop.mapreduce.lib.input.*;

public class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private String pattern= "^[a-z][a-z0-9]*$";

public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
//line added
InputSplit inputSplit = context.getInputSplit();
String fileName = ((FileSplit) inputSplit).getPath().getName();

while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
String stringWord = word.toString().toLowerCase();
if ((stringWord).matches(pattern)){
//context.write(new Text(stringWord), one);
context.write(new Text(stringWord), one);
context.write(new Text(fileName), one);
//System.out.println(fileName);
}
}
}
}

最佳答案

你可以通过写 word 来实现。如keyfilenamevalue .现在在你的 reducer 中为每个文件初始化单独的计数器并更新它们。一旦针对特定键迭代了所有值,然后将每个文件的计数器写入上下文。

在这里您知道您只有四个文件,因此您可以硬编码四个变量。请记住,您需要为在 reducer 中处理的每个新键重置变量。

如果文件数量更多,则可以使用 Map.在 map 上,filename将是 key并继续更新value .

关于java - 每个文件计数的 WordCount 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32969870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com