文字列内で単語が何回出現するかを追跡するプログラムがあります。また、カウントされる単語の直後に来る単語についていく必要があり、その特定の単語の後に何回来るかについていく必要があります。
例: こんにちは、名前はボブです。私の名前はボブです。あなたの名前を教えてください。
name という単語を検索すると、出力が必要になります: name - 2, is - 2, please - 1. (特にその形式ではありませんが、たとえば。)
バッファリングされたリーダーでテキストファイルを読み取り、読み取ったテキストをすべて小文字として文字列に入れます。
句読点がないように「正規表現」し、各スペースの後に文字列を分割するコードがあります。
次に、これを配列に入れ、次に各単語の出現回数をカウントするハッシュマップに入れます。
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 に保存するので、文字列内の単語を検索するだけでは不十分です。最初に単語とそのカウントをドキュメントとして保存し、次に続く単語とそのカウントを、それらが従う単語のサブドキュメントのリストとして保存し、データベースを検索して情報を取得する必要があります。文字列の一般的な単語についてはそれを行うことができます。私の問題は、上記のように続く単語に追いつくことから生じます。