用java代码写单词统计

本文介绍了一种使用Java进行文件读取的方法,并通过字节流和字符流结合的方式实现单词频率的统计。该方法首先利用FileInputStream读取文件内容,再通过InputStreamReader和BufferedReader将数据转换为便于处理的形式。最终,通过HashMap存储每个单词出现的次数。

先利用io流
FileInputStream字节流读取数据,转换成字符流InputStreamReader,
用BufferedReader字符缓冲流 因为有readline()每次读取一行的方法

 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/wcinput/wc.txt")));
 //map 存储键值对
        Map<String, Integer> map = new HashMap<>();
      String line = "";
        while ((line = br.readLine()) != null) {  
        String[] arr = line.split(" ");
            for (String word : arr) {
            if (map.get(word) == null) {
                    map.put(word, 1);
                      } else {
                    map.put(word, map.get(word) + 1);
                }
                
    //map集合中keySet() 把所有的key放到set集合中  遍历map集合中所有的key
        Set<String> set = map.keySet();
          for (String str : set) {
            System.out.println(str + " " + map.get(str));
        }
Java 中实现单词统计功能可以通过多种方式完成,具体实现取决于应用场景,例如是本地统计、处理文本文件,还是基于 Hadoop 的分布式处理。以下是几种常见的实现方式: ### 本地 Java 实现单词统计 以下是一个简单的 Java 示例,用于统计字符串中每个单词的出现次数。该示例通过正则表达式去除标点符号,并将单词转换为小以避免大小差异带来的问题: ```java import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WordCount { public static void main(String[] args) { String text = "Hello world! Hello everyone. Welcome to the world of Java."; Map<String, Integer> wordCountMap = new HashMap<>(); // 使用正则表达式匹配单词 Pattern pattern = Pattern.compile("\\b\\w+\\b"); Matcher matcher = pattern.matcher(text.toLowerCase()); while (matcher.find()) { String word = matcher.group(); wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1); } // 输出结果 for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } } ``` ### 基于 Hadoop 的 MapReduce 实现单词统计 如果你希望在 Hadoop 平台上运行词频统计程序,可以使用 MapReduce 模型。以下是一个基本的 Mapper 和 Reducer 实现: #### Mapper 类 ```java import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.util.StringTokenizer; public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken().toLowerCase()); context.write(word, one); } } } ``` #### Reducer 类 ```java import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } context.write(key, new IntWritable(sum)); } } ``` #### Driver 类 ```java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCountDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCountDriver.class); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` ### 代码说明 1. **本地实现**:适用于单机环境下的单词统计任务,适合处理小规模文本数据。 2. **Hadoop MapReduce 实现**:适用于大规模数据集的分布式处理,利用 Hadoop 集群进行词频统计。Mapper 输出 `<单词, 1>`,Reducer 对每个单词的计数进行累加。 这些代码可以根据具体需求进行扩展,例如增加对特殊字符的处理、忽略常见停用词等。此外,在实际部署 Hadoop 作业时,需要注意构建和打包过程,确保 JAR 文件中不包含不必要的文件夹(如 `META-INF` 和 `license`)[^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值