从文章中统计不同单词出现的次数

    xiaoxiao2021-03-25  50

    public class ReadEnglishText { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("src.txt"); InputStreamReader isb=new InputStreamReader(fis,"utf-8"); BufferedReader br=new BufferedReader(isb); //定义一个缓冲字符串,用于存储文章中的字符串 StringBuffer sbuf=new StringBuffer(); String line=null; //用来存储每个字符串及其对应的次数 Map<String,Integer> map=new HashMap<String,Integer>(); //按行进行读取 while((line=br.readLine())!=null){ sbuf.append(line); } br.close(); String str=sbuf.toString(); //根据正则表达式,将读回来的字符串拆分为字符串数组 String[] arrys=str.split("[,.\\s]");//本案例是统计英文的,若统计中文可以按其他符号拆分 for(int i=0;i<arrys.length;i++){ //判断是否出现过,如果出现过则统计次数加1 if(map.containsKey(arrys[i])){ map.put(arrys[i], map.get(arrys[i])+1); }else{//没出现过,添加到map中 map.put(arrys[i],1); } } //遍历map Set<Entry<String,Integer>> set=map.entrySet(); for(Entry<String,Integer> se:set){ System.out.println(se.getKey()+"出现了"+se.getValue()+"次"); } } }
    转载请注明原文地址: https://ju.6miu.com/read-37787.html

    最新回复(0)