java统计一段英文中单词及个数

来源:互联网 发布:java环境变量配置linux 编辑:程序博客网 时间:2024/05/17 23:09
public static void countWords(String str){        Map<String, Integer> map=new HashMap<String, Integer>();                Pattern p=Pattern.compile("\\b[a-zA-Z-]+\\b");//正则表达式        Matcher m=p.matcher(str);        while(m.find()){            String mstr=m.group();            if(map.containsKey(mstr)){                map.put(mstr,map.get(mstr)+1);            }else{                map.put(mstr, 1);            }        }        Set<Entry<String, Integer>> entrySet = map.entrySet();        Iterator<Entry<String,Integer>> it=entrySet.iterator();        while(it.hasNext()){            Entry<String, Integer> next = it.next();            System.out.println(next.getKey()+" 个数:"+next.getValue());        }    }