java 字符串詞頻統(tǒng)計實例代碼
更新時間:2013年03月30日 09:51:29 作者:
java 字符串詞頻統(tǒng)計實例代碼,需要的朋友可以參考一下
復(fù)制代碼 代碼如下:
package com.gpdi.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordsStatistics {
class Obj {
int count ;
Obj(int count){
this.count = count;
}
}
public List<WordCount> statistics(String word) {
List<WordCount> rs = new ArrayList<WordCount>();
Map <String,Obj> map = new HashMap<String,Obj>();
if(word == null ) {
return null;
}
word = word.toLowerCase();
word = word.replaceAll("'s", "");
word = word.replaceAll(",", "");
word = word.replaceAll("-", "");
word = word.replaceAll("\\.", "");
word = word.replaceAll("'", "");
word = word.replaceAll(":", "");
word = word.replaceAll("!", "");
word = word.replaceAll("\n", "");
String [] wordArray = word.split(" ");
for(String simpleWord : wordArray) {
simpleWord = simpleWord.trim();
if (simpleWord != null && !simpleWord.equalsIgnoreCase("")) {
Obj cnt = map.get(simpleWord);
if ( cnt!= null ) {
cnt.count++;
}else {
map.put(simpleWord, new Obj(1));
}
}
}
for(String key : map.keySet()) {
WordCount wd = new WordCount(key,map.get(key).count);
rs.add(wd);
}
Collections.sort(rs, new java.util.Comparator<WordCount>(){
@Override
public int compare(WordCount o1, WordCount o2) {
int result = 0 ;
if (o1.getCount() > o2.getCount() ) {
result = -1;
}else if (o1.getCount() < o2.getCount()) {
result = 1;
}else {
int strRs = o1.getWord().compareToIgnoreCase(o2.getWord());
if ( strRs > 0 ) {
result = 1;
}else {
result = -1 ;
}
}
return result;
}
});
return rs;
}
public static void main(String args[]) {
String word = "Pinterest is might be aa ab aa ab marketer's dream - ths site is largely used to curate products " ;
WordsStatistics s = new WordsStatistics();
List<WordCount> rs = s.statistics(word);
for(WordCount word1 : rs) {
System.out.println(word1.getWord()+"*"+word1.getCount());
}
}
}
相關(guān)文章
java批量采集豌豆莢網(wǎng)站Android應(yīng)用圖標(biāo)和包名
這篇文章主要介紹了java批量采集豌豆莢網(wǎng)站Android應(yīng)用圖標(biāo)和包名,主要用在做主題時替換這些常見應(yīng)用的圖片,需要的朋友可以參考下2014-06-06Mybatis中mapper.xml實現(xiàn)熱加載介紹
大家好,本篇文章主要講的是Mybatis中mapper.xml實現(xiàn)熱加載介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01詳解Spring Boot Mysql 版本驅(qū)動連接池方案選擇
這篇文章主要介紹了詳解Spring Boot Mysql 版本驅(qū)動連接池方案選擇,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08SpringBoot全局異常捕獲參數(shù)以及參數(shù)異常的解決方案
這篇文章主要介紹了SpringBoot全局異常捕獲參數(shù)以及參數(shù)異常的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-05-05Spring整合Kaptcha谷歌驗證碼工具的開發(fā)步驟
這篇文章主要介紹了Spring整合Kaptcha谷歌驗證碼工具的開發(fā)步驟,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01