编写一个程序,统计一个文本文件所包含的不同单词的个数,并将结果保存在另一个文件中。

本文介绍了一个使用Java编写的程序,该程序能够统计指定文本文件中不同单词的数量,并按出现次数排序输出结果到新文件。

题目:编写一个程序,统计一个文本文件所包含的不同单词的个数,并将结果保存在另一个文件中。输出文件的格式为:每个单词占用一行,其内容包括单词本身及其出现的次数;各单词之间要按照从小到大的顺序排列。

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

/**
 * @author LL Leung
 */
public class WordCount {

    static ArrayList<String> wordList = new ArrayList<String>();

    public static void main(String[] args)throws FileNotFoundException{
        //读入"word.txt"内容并存进字符串中
        Scanner input = new Scanner(new File("word.txt"));
        String s = input.nextLine();

        //分割字符串并存进字符串数组中
        String [] strArr = s.split(" ");
        HashMap<String, Integer> hashMap = new HashMap<String,Integer>();

        //遍历字符串数组
        for(String word:strArr){
            //求出不同单词个数
            if(!wordList.contains(word.toLowerCase())){
                wordList.add(word.toLowerCase());
            }
            //求出每一个单词出现的个数
            Integer currentCount = hashMap.get(word);
            if(currentCount == null){
                currentCount = 0;
            }
            hashMap.put(word,++currentCount);
        }

        System.out.println("不同单词个数为:" + wordList.size());

        //创建新文件"newDemo2.txt"并将"排序单词出现次数"等内容存进新文件中
        try{
            FileOutputStream fos = new FileOutputStream("newDemo.txt",false);
            fos.write(sort(hashMap).getBytes());
            //关闭文件流
            fos.close();
        }catch(IOException ex){
            System.out.println("无法打开文件!");
        }
    }

    /**
     * 将"hashMap"中的“value”值进行排序
     * @param hashMap
     * @return
     */
    public static String sort(Map<String,Integer> hashMap){
        StringBuilder str = new StringBuilder("不同单词个数为:" + wordList.size() + "\r\n");
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(hashMap.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue() < o2.getValue()) {
                    return -1;
                } else if (o1.getValue() > o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });

        //打印信息
        for (Map.Entry<String, Integer> id : list) {
            str.append("单词:").append(id.getKey()).append(" 出现次数:").append(id.getValue()).append("\r\n");
        }
        return str.toString();
    }
}

原文本"word.txt"内容:

程序运行成功后创建的"newDemo.txt"文本:

可以使用MapReduce或Spark框架来编写大数据程序统计文本文件中首字母相同的单词个数,以下是两种框架的实现方法: ### MapReduce实现 #### 思路分析 - **Mapper阶段**:将每一行文本拆分为单词,输出键值对`<单词首字母, 1>`。 - **Reducer阶段**:对相同首字母的键值对进行累加,输出`<首字母, 单词个数>`。 #### 代码示例 ```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 org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import java.io.IOException; // Mapper类 class WordInitialMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text wordInitial = new Text(); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(" "); for (String word : words) { if (word.length() > 0) { String initial = String.valueOf(word.charAt(0)).toUpperCase(); wordInitial.set(initial); context.write(wordInitial, one); } } } } // Reducer类 class WordInitialReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } // 主类 public class WordInitialCount { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "Word Initial Count"); job.setJarByClass(WordInitialCount.class); job.setMapperClass(WordInitialMapper.class); job.setCombinerClass(WordInitialReducer.class); job.setReducerClass(WordInitialReducer.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); } } ``` ### Spark实现 #### 思路分析 - 读取文本文件,将每一行拆分为单词。 - 提取每个单词的首字母,转换为大写。 - 对首字母进行计数。 #### 代码示例 ```scala import org.apache.spark.sql.SparkSession object WordInitialCountSpark { def main(args: Array[String]): Unit = { val spark = SparkSession.builder() .appName("Word Initial Count Spark") .master("local[*]") .getOrCreate() val sc = spark.sparkContext val textFile = sc.textFile(args(0)) val words = textFile.flatMap(line => line.split(" ")) val initials = words.filter(_.length > 0).map(word => word.charAt(0).toUpper.toString) val initialCounts = initials.map(initial => (initial, 1)).reduceByKey(_ + _) initialCounts.collect().foreach(println) spark.stop() } } ```
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值