当前位置: 移动技术网 > IT编程>开发语言>Java > java统计字符串单词个数的方法解析

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

运行结果:

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网