您的位置:首页 > 其它

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

2017-03-12 22:32 316 查看
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()+"次");
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息