欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java统计字符串单词个数的方法解析

时间:2021-02-18 11:21:15|栏目:JAVA代码|点击:

在一些项目中可能需要对一段字符串中的单词进行统计,我在这里写了一个简单的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);   }

运行结果:

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

上一篇:深入解析Java的Servlet过滤器的原理及其应用

栏    目:JAVA代码

下一篇:Java 对 Cookie增删改查的实现示例

本文标题:java统计字符串单词个数的方法解析

本文地址:http://www.codeinn.net/misctech/65446.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有