java统计文本中出现相同单词数量

渡星河
2023-01-09 / 0 评论 / 10 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年01月09日,已超过619天没有更新,若内容或图片失效,请留言反馈。

题目

public class Homework {
    public static void main(String[] args) {
        try(FileInputStream fis = new FileInputStream("word.txt");
            FileOutputStream fos = new FileOutputStream("wordcount.txt")) {
            //定义字节数组存储读取到的内容
            byte[] bytes = new byte[1024];//一次读取1KB
            //因为文件的内容可能大于1KB,所以我们需要循环读取多次
            StringBuilder sb = new StringBuilder();//用于存放获取到的所有内容
            while (fis.read(bytes) != -1) {
               sb.append(new String(bytes));
            }
            String content = sb.toString();
            //替换掉sb里的换行符
            content = content.replace("\r", " ");
            content = content.replace("\n", " ");
            content = content.replace("\r\n", " ");
            //把内容转成小写
            content = content.toLowerCase();
            //按空格切分字符串
            String[] contents = content.split(" ");
            HashMap<String, Integer> map = new HashMap<>();//用于统计每个单词出现的次数
            for (String word : contents) {
                if (map.containsKey(word)) {//如果key相同,取出value,让其加1,然后再存回去
                    map.put(word, map.get(word) + 1);
                } else {
                    map.put(word, 1);
                }
            }
            //把map的内容写到文件wordcount.txt里,每个key-value存做一行
            //遍历map
            for (Map.Entry<String,Integer> entry : map.entrySet()) {
                fos.write((entry.getKey() + " " + entry.getValue() + "个\n").getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
1

评论 (0)

取消