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

网友投稿 252 2023-06-20


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 map = new HashMap();

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 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------kSMIA-------------");

}

}

测试代码:

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); }

运行结果:

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用BootStrap实现表格隔行变色及hover变色并在需要时出现滚动条
下一篇:Bootstrap3 图片(响应式图片&图片形状)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~