2010-11-16 86 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); 
相关问题