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

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()+"次");
		    }
		
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值