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

来源:互联网 发布:算法导论 编辑:程序博客网 时间:2024/05/16 10:09
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++){//判断是否出现过,如果出现过则统计次数加1if(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()+"次");    }}}

0 0