java統(tǒng)計(jì)字符串單詞個(gè)數(shù)的方法解析
在一些項(xiàng)目中可能需要對(duì)一段字符串中的單詞進(jìn)行統(tǒng)計(jì),我在這里寫(xiě)了一個(gè)簡(jiǎn)單的demo,有需要的同學(xué)可以拿去看一下。
不說(shuō)廢話了直接貼代碼:
實(shí)現(xiàn)代碼:
/**
* 統(tǒng)計(jì)各個(gè)單詞出現(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)為小寫(xiě)
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);
}
}
}
//輸出到控制臺(tái)
System.out.println("各個(gè)單詞出現(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-------------------");
}
}
測(cè)試代碼:
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); }
運(yùn)行結(jié)果:

后面還有一些沒(méi)有全部截下來(lái)
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
java中List集合及其實(shí)現(xiàn)類(lèi)的方法詳解
本篇文章給大家?guī)?lái)的內(nèi)容是關(guān)于java中List集合及其實(shí)現(xiàn)類(lèi)的方法介紹(附代碼),有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。下面我們就來(lái)學(xué)習(xí)一下吧2019-06-06
SpringSecurity HttpSecurity 類(lèi)處理流程分析
SpringSecurity在SSM項(xiàng)目中使用基于配置文件,通過(guò)XML標(biāo)簽定義認(rèn)證信息,HttpSecurity在SpringBoot中通過(guò)代碼配置實(shí)現(xiàn)與XML相同功能,詳細(xì)介紹了HttpSecurity的類(lèi)結(jié)構(gòu)、處理過(guò)程及其與SecurityBuilder的關(guān)系,感興趣的朋友一起看看吧2024-09-09
springboot引入druid解析sql的過(guò)程
在開(kāi)發(fā)中,有時(shí)我們可能會(huì)需要獲取SQL中的表名,那么因?yàn)椴煌臄?shù)據(jù)源類(lèi)型SQL會(huì)存在部分差異,那么我們就可以使用alibaba 的druid包實(shí)現(xiàn)不同的數(shù)據(jù)源類(lèi)型的sql解析,需要的朋友可以參考下2023-08-08
java日志LoggerFactory.getLogger的用法及說(shuō)明
這篇文章主要介紹了java日志LoggerFactory.getLogger的用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Java 執(zhí)行CMD命令或執(zhí)行BAT批處理方式
這篇文章主要介紹了Java 執(zhí)行CMD命令或執(zhí)行BAT批處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Spring容器注冊(cè)組件實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Spring容器注冊(cè)組件實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03

