java统计字符串单词个数的方法解析
更新时间:2017年01月04日 09:06:22 作者:littleFatty
在一些项目中可能需要对一段字符串中的单词进行统计,本文在这里分享了一个简单的demo,有需要的朋友可以拿去看一下
在一些项目中可能需要对一段字符串中的单词进行统计,我在这里写了一个简单的demo,有需要的同学可以拿去看一下。
不说废话了直接贴代码:
实现代码:
/** * 统计各个单词出现的次数 * @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 + "\n\t\t" + num + "次\n-------------------"); } }
测试代码:
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); }
运行结果:
后面还有一些没有全部截下来
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!
相关文章
Spring中的监听器SpringApplicationRunListener详解
这篇文章主要介绍了Spring中的监听器SpringApplicationRunListener详解,命名我们就可以知道它是一个监听者,分析springboot启动流程我们会发现,它其实是用来在整个启动流程中接收不同执行点事件通知的监听者,需要的朋友可以参考下2023-11-11java微信小程序步数encryptedData和开放数据解密的实现
这篇文章主要介绍了java微信小程序步数encryptedData和开放数据解密的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-09-09SpringMVC + servlet3.0 文件上传的配置和实现代码
本篇文章主要介绍了SpringMVC + servlet3.0 文件上传的配置和实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2017-04-04
最新评论