java統(tǒng)計字符串單詞個數(shù)的方法解析
更新時間:2017年01月04日 09:06:22 作者:littleFatty
在一些項目中可能需要對一段字符串中的單詞進行統(tǒng)計,本文在這里分享了一個簡單的demo,有需要的朋友可以拿去看一下
在一些項目中可能需要對一段字符串中的單詞進行統(tǒng)計,我在這里寫了一個簡單的demo,有需要的同學(xué)可以拿去看一下。
不說廢話了直接貼代碼:
實現(xiàn)代碼:
/**
* 統(tǒng)計各個單詞出現(xiàn)的次數(shù)
* @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];
//轉(zhuǎn)為小寫
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("各個單詞出現(xiàn)的頻率為:");
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); }
運行結(jié)果:

后面還有一些沒有全部截下來
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
SpringSecurity HttpSecurity 類處理流程分析
SpringSecurity在SSM項目中使用基于配置文件,通過XML標(biāo)簽定義認(rèn)證信息,HttpSecurity在SpringBoot中通過代碼配置實現(xiàn)與XML相同功能,詳細(xì)介紹了HttpSecurity的類結(jié)構(gòu)、處理過程及其與SecurityBuilder的關(guān)系,感興趣的朋友一起看看吧2024-09-09
java日志LoggerFactory.getLogger的用法及說明
這篇文章主要介紹了java日志LoggerFactory.getLogger的用法及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Java 執(zhí)行CMD命令或執(zhí)行BAT批處理方式
這篇文章主要介紹了Java 執(zhí)行CMD命令或執(zhí)行BAT批處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

