• java统计字符串单词的个数


    在一些项目中可能需要对一段字符串中的单词进行统计,我在这里写了一个简单的demo,有需要的同学可以拿去看一下。

    本人没怎么写个播客,如果有啥说的不对的地方,欢迎大家指正。

    查询指定字符串出现次数可以直接使用:StringUtils.countMatches(str, sub)

    统计所有单词出现次数代码:

            /** 
             * 统计各个单词出现的次数 
             * @param text 
             */  
            public static void findEnglishNum(String text){  
                //找出所有的单词  
                String[] array = {".", " ", "?", "!"};  
                for (int i = 0; i < array.length; i++) {  
                    text = text.replace(array[i],",");  
                }  
                String[] textArray = text.split(",");  
                  
                //遍历 记录  
                Map<String, Integer> map = new HashMap<String, Integer>();  
                for (int i = 0; i < textArray.length; i++) {  
                    String key = textArray[i];  
                    //转为小写  
                    String key_l = key.toLowerCase();  
                    if(!"".equals(key_l)){  
                        Integer num = map.get(key_l);  
                        if(num == null || num == 0){  
                            map.put(key_l, 1);  
                        }else if(num > 0){  
                            map.put(key_l, num+1);  
                        }  
                    }  
                }  
                //输出到控制台  
                System.out.println("各个单词出现的频率为:");  
                Iterator<String> iter = map.keySet().iterator();  
                while(iter.hasNext()){  
                    String key = iter.next();  
                    Integer num = map.get(key);  
                    System.out.println(key + "
    		" + num + "次
    -------------------");  
                }  
            }  

    测试代码:

        public static void main(String[] args) {  
                String text = "Welcome welcome to ADempiere, a commons-based peer-production of Open Source ERP Applications. This Wiki is for the global community to contribute and share know-how and domain expertise. We hope you can find as much open information and participate in making it most usable for everyone. This project has a bazaar of Citizens with a Community Council Team which work in theFunctional Team and Technical Team along the Software Development Procedure supported and funded by the foundation ADempiere";  
                  
                findEnglishNum(text);          }  

    运行结果:

    后面还有一些没有全部截下来


    本人代码功力不够深厚,如果代码中有什么不对或不好的地方,欢迎各位大神指点!可怜

  • 相关阅读:
    【数据库】数据表解锁
    【数据库】Oracle数据备份恢复
    【数据库】mysql没有密码无法登录的解决办法
    【设计模式】设计模式(一)-- 大话设计模式读书笔记
    【Linux】Linux常用命令及操作 (一)
    【GIT】git详解
    【python】Anaconda4 linux/windos安装
    【心 得】关于此博客
    eclipse中的.project 和 .classpath文件的具体作用
    Oracle忘记密码处理
  • 原文地址:https://www.cnblogs.com/LFBlog/p/6240906.html
Copyright © 2020-2023  润新知