java小算法—统计句子中每个单词出现的次数

来源:互联网 发布:spss19.0破解软件 编辑:程序博客网 时间:2024/05/22 10:56
public class demo2 {


public static void main(String[] args) {
String words="Look buddy, U got work hard and put yourself in your java, Once you learned the heart of the java, I can guarantee that you win.";

//正则匹配
String reg="[a-zA-Z]+";
Pattern p=Pattern.compile(reg);
Matcher m=p.matcher(words);

//存放单词的集合
HashMap<String, Integer> map=new HashMap<String, Integer>();
int count=0;//单词总数
while(m.find()){
count++;
String w=m.group();
if(null==map.get(w)){//此单词集合中没有 添加 数量为1
map.put(w, 1);
}else{//已有 添加 数量+1
int x=map.get(w);
map.put(w,x+1);
}
}
//单词总数
System.out.println("单词总数:"+count);
//遍历集合keySet
Set<String> set=map.keySet();
Iterator<String> i1=set.iterator();
while(i1.hasNext()){
String key=i1.next();//key
Integer value=map.get(key);//值
System.out.println("单词:"+key+"    出现次数:"+value);
System.out.println("------------------------------------------");
}
}

}


结果:

单词总数:26
单词:Look    出现次数:1
------------------------------------------
单词:buddy    出现次数:1
------------------------------------------
单词:work    出现次数:1
------------------------------------------
单词:heart    出现次数:1
------------------------------------------
单词:put    出现次数:1
------------------------------------------
单词:can    出现次数:1
------------------------------------------
单词:your    出现次数:1
------------------------------------------
单词:you    出现次数:2
------------------------------------------
单词:win    出现次数:1
------------------------------------------
单词:the    出现次数:2
------------------------------------------
单词:I    出现次数:1
------------------------------------------
单词:in    出现次数:1
------------------------------------------
单词:and    出现次数:1
------------------------------------------
单词:U    出现次数:1
------------------------------------------
单词:that    出现次数:1
------------------------------------------
单词:of    出现次数:1
------------------------------------------
单词:Once    出现次数:1
------------------------------------------
单词:learned    出现次数:1
------------------------------------------
单词:guarantee    出现次数:1
------------------------------------------
单词:java    出现次数:2
------------------------------------------
单词:yourself    出现次数:1
------------------------------------------
单词:got    出现次数:1
------------------------------------------
单词:hard    出现次数:1
------------------------------------------

阅读全文
0 0
原创粉丝点击