我想知道,如果我有一個單一的行字符串,那麼如何使用簡單的java代碼來計算該字符串中特定單詞的頻率?!如何統計一行中特定單詞的頻率?
在此先感謝..
我所尋找的是在Java是爲了用一句話來搜索一個特定的詞的樣本邏輯代碼。我正在構建一個垃圾郵件過濾器,需要閱讀該行並對其進行分類。
我想知道,如果我有一個單一的行字符串,那麼如何使用簡單的java代碼來計算該字符串中特定單詞的頻率?!如何統計一行中特定單詞的頻率?
在此先感謝..
我所尋找的是在Java是爲了用一句話來搜索一個特定的詞的樣本邏輯代碼。我正在構建一個垃圾郵件過濾器,需要閱讀該行並對其進行分類。
StringUtils.countMatches(string, searchedFor);
由空格第一分裂(參見String#split)
然後使用映射的話與頻率圖。
String [] words = line.split(" ");
Map<String,Integer> frequency = new Map <String,Integer>();
for (String word:words){
Integer f = frequency.get(word);
frequency.put(word,f+1);
}
然後你就可以找出一個特定的詞:
frequency.get(word)
幾種方法:
選項1 & 2有試圖找出如果你的字恰好是最後上線(以及需要增加一個額外的計數)的開銷
選項3要求您能夠形成正則表達式語法
方案4陳舊
您可以使用正則表達式。代碼的一個例子是:
public int count(String word, String line){
Pattern pattern = Pattern.compile(word);
Matcher matcher = pattern.matcher(line);
int counter = 0;
while (matcher.find())
counter++;
return counter;
}
使用Guava庫:
MultiSet(當需要的所有單詞計數使用)
String line="Hello world bye bye world";
Multiset<String> countStr=HashMultiset.create(Splitter.on(' ').split(line));
System.out.println(countStr.count("Hello")); //gives count of the word 'Hello'
Iterators(使用時需要的只有幾個字計數)
String line="Hello world bye bye world";
Iterable<String> splitStr=Splitter.on(' ').split(line);
System.out.println(Iterables.frequency(splitStr, "Hello"));
後Googleing和小書房裏,我得到這個東西__可能是有益的
String str="hello new demo hello";
Map<String,Integer> hmap= new HashMap<String,Integer>();
for(String tempStr : str.split(" "))
{
if(hmap.containsKey(tempStr))
{
Integer i=hmap.get(tempStr);
i+=1;
hmap.put(tempStr,i);
}
else
hmap.put(tempStr,1);
}
System.out.println(hmap);
我想這算作簡單的Java代碼:) – Tom 2010-11-16 23:27:29