计算单词数量

来源:互联网 发布:东欧西欧知乎 编辑:程序博客网 时间:2024/04/30 13:44

                                                                                                     JAVA  计算单词数量

    这是我在CSND的第一篇博客文章,记录一下我学习JAVA的小小成果。

    package abc;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class LetterCount {
       static String str = "this 'is' a good man, so I will say to her, I love you!" +
                                        " this so a so man, so I \"will\" say to her, I love you!";
       static String rex1 = "[.,;:!@#$%^&*()]";    // 匹配单词尾部出现在标点符号
       static String rex2 = "[\"\']";    //匹配单词的引号
       public static void main(String[] args) {
       String[] str1 = str.split(" "); // 分割整个文本,并把们存储到一个字符串数组中
       Map<String,Integer> map = new HashMap<String,Integer>();
       List<String> letter = new ArrayList<String>();
       Pattern pattern1 = Pattern.compile(rex1);
       Pattern pattern2 = Pattern.compile(rex2);
       for(int i=0;i<str1.length;i++){
           Matcher matcher1 = pattern1.matcher(str1[i].substring(str1[i].length()-1,str1[i].length()));
           Matcher matcher2 = pattern2.matcher(str1[i].substring(0,1));
           Matcher matcher3 = pattern2.matcher(str1[i].substring(str1[i].length()-1,str1[i].length()));
           if(matcher1.matches()){
               letter.add(str1[i].substring(0,str1[i].length()-1));  //
           }else if(matcher2.matches()&&matcher3.matches()){
               letter.add(str1[i].substring(1,str1[i].length()-1));
           }else{
               letter.add(str1[i].substring(0,str1[i].length()));
           }
       }
       Iterator<String> it = letter.iterator();
       while(it.hasNext()){
           String key =  (String)it.next();
           if(!map.containsKey(key)){
               map.put(key, 1);
           }else{
               map.put(key,map.get(key)+1);
           }
       }
       
       Set<String> keyset = map.keySet();
       Iterator<String> it1 = keyset.iterator();
       while(it1.hasNext()){
           String key = it1.next();
           Integer value = map.get(key);
           System.out.println(key +"----->" +value);
       }
}
}


0 0
原创粉丝点击