统计各个单词出现的次数

本文介绍了一个简单的Java程序,该程序用于统计给定英文文本中各个单词出现的频率,并将结果输出到控制台。通过对输入文本进行预处理,去除标点符号并转换为小写形式,使用HashMap来记录每个单词的出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class StStringNum {
    /*
     * 统计各个单词出现的次数
     * 
     * @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);

    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值