Java 统计单词频数

输出单个文件中的 N 个英语单词出现的次数

定义双列集合,将单词不重复的读入一列中,另一列用来计数

import java.io.BufferedReader;
import java.util.Arrays;
import java.io.FileReader;
import java.io.IOException;
import java.util.TreeMap;
public class Statistics {
    public static void main(String args[])throws IOException {
        char[] ss = new char[20];
        int temp;
        int i = 0;
        String cha = null;
        BufferedReader br = new BufferedReader(new FileReader("word.txt"));//建立文件流        
        TreeMap<String, Integer> word = new TreeMap<>();//建立双列集合        
        while((temp = br.read()) != -1) {            
            char c = (char)temp;
            if(((c>=65) && (c<=90)) || ((c>=97) && (c<=122))) {
                ss[i] = c;
                i++;
            }            
            else {
                cha = Arrays.toString(ss);
                cha = cha.replaceAll("[\\[\\]]","");
                cha = cha.replaceAll(",","");
                cha = cha.replaceAll(" ","");
                word.put(cha, !word.containsKey(cha) ? 1 : word.get(cha) + 1);
                i = 0;
                ss =new char[20];
            }
        }
        br.close();
        //输出
        for(String key : word.keySet()) {
            Integer value=word.get(key);
            System.out.println(key+"="+value);
        }        
    }    
}

 

posted @ 2018-10-11 20:59  L、、、  阅读(392)  评论(0编辑  收藏  举报