2010-11-16 44 views
4

我想知道,如果我有一個單一的行字符串,那麼如何使用簡單的java代碼來計算該字符串中特定單詞的頻率?!如何統計一行中特定單詞的頻率?

在此先感謝..


我所尋找的是在Java是爲了用一句話來搜索一個特定的詞的樣本邏輯代碼。我正在構建一個垃圾郵件過濾器,需要閱讀該行並對其進行分類。

回答

9

StringUtilscommons-lang具有:

StringUtils.countMatches(string, searchedFor); 
+1

我想這算作簡單的Java代碼:) – Tom 2010-11-16 23:27:29

3

由空格第一分裂(參見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) 
0

幾種方法:

  1. 使用拆分
  2. 使用斷詞
  3. 使用正則表達式
  4. 使用好的舊循環a第二字符串操作(即的indexOf()等)

選項1 & 2有試圖找出如果你的字恰好是最後上線(以及需要增加一個額外的計數)的開銷

選項3要求您能夠形成正則表達式語法

方案4陳舊

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; 
} 
2

使用Guava庫:

  1. 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' 
    
  2. Iterators使用時需要的只有幾個字計數)

    String line="Hello world bye bye world"; 
    Iterable<String> splitStr=Splitter.on(' ').split(line); 
    System.out.println(Iterables.frequency(splitStr, "Hello")); 
    
1

後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); 
相關問題