在一些项目中可能需要对一段字符串中的单词进行统计,我在这里写了一个简单的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-------------------");
}
}
测试代码:
立即学习“Java免费学习笔记(深入)”;
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); }运行结果:
由逍遥网店系统修改而成,修改内容如下:前台商品可以看大图功能后台商品在线添加编辑功能 (允许UBB)破解了访问统计系统增加整合了更加强大的第三方统计系统 (IT学习者v1.6)并且更新了10月份的IP数据库。修正了后台会员订单折扣金额处理错误BUG去掉了会员折扣价这个功能,使用市场价,批发价。这样符合实际的模式,批发价非会员不可看修正了在线编辑无法使用 “代码&rdqu
0

后面还有一些没有全部截下来
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多PHP中文网!
更多java统计字符串单词个数的方法解析相关文章请关注PHP中文网!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
C++高性能并发应用_C++如何开发性能关键应用
Java AI集成Deep Java Library_Java怎么集成AI模型部署
Golang后端API开发_Golang如何高效开发后端和API
Python异步并发改进_Python异步编程有哪些新改进
C++系统编程内存管理_C++系统编程怎么与Rust竞争内存安全
Java GraalVM原生镜像构建_Java怎么用GraalVM构建高效原生镜像
Python FastAPI异步API开发_Python怎么用FastAPI构建异步API
C++现代C++20/23/26特性_现代C++有哪些新标准特性如modules和coroutines
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号