字计数循环

时间:2013-07-01 15:34:23

标签: mongodb-java

我有一个程序可以跟上字符串中单词出现的次数。我还需要能够跟上在计算的单词之后直接出现的单词,并跟上它在该单词之后出现的次数。

示例:您好,名字是Bob。鲍勃我的名字是。你能告诉我你的名字吗?

如果我搜索单词名称,我需要输出:name - 2,is - 2,please - 1.(特别是那种格式,但是例如。)

我用缓冲读取器读取了一个文本文件,并将读取的文本作为全部小写字母放入字符串中。

我的代码是“正则表达式”,因此没有标点符号,然后在每个空格后分​​割字符串。

然后我把它放到一个数组中,然后放在一个计算每个单词出现次数的hashmap中。

package model;

import java.util.HashMap;

/**
 * Word Class
 */
public class Word {

public String word;
public int count;

/**
 * Empty constructor.
 */
public Word() {

}

/**
 * Constructor to access word and it occurrence.
 * 
 * @param word - the word in the array
 * @param count - the words occurrence in the array
 */
public Word(String word, int count) {

    this.word = word;
    this.count = count;
}

/**
 * Compares words to see if they are the same word.
 * 
 * @param word - the word to compare
 * @return int - the current count of the word's occurrence
 */
public int compareTo(Word otherWord) {

    if(this.count==otherWord.count){

        return this.word.compareTo(otherWord.word);
    }

    return otherWord.count-this.count;
}

/**
 * Puts the words into an array according to their frequency.
 * 
 * @param words[] - the array to be counted
 * @return Word[] - the array of counted words
 */
public Word[] getFrequentWords(String words[]){

    HashMap<String,Word> map = new HashMap<String,Word>();

    for(String s:words){

        Word w = map.get(s);
        if(w==null)
            w = new Word(s, 1);
        else
            w.count++;
        map.put(s, w);
    }

    Word[] list = map.values().toArray(new Word[]{});

    return list;
}

}

我将单词及其各自的计数存储在MongoDB中,所以它不仅仅是在字符串中搜索单词。我需要先将单词及其计数存储为文档,然后将后面的单词及其计数存储在它们所遵循的单词的子文档中,然后搜索数据库以获取信息。我可以为字符串的一般单词做到这一点,我的问题来自于跟上上面提到的单词。

0 个答案:

没有答案