T.newGuy1620 T.newGuy1620 - 3 months ago 11
Java Question

how to count how many times each word appears?

I'm trying to count how many times each word from uniqueBagOfWords appears in each sentence from the 'sentences' arraylist.

uniqueBagOFwords = [i, like, to, play, tennis, think, football, needs, big, changes]

I would like to be able to count how many times a word from uniqueBagOfWords appears in each sentence....At the moment I can only add 1 to the position of the word if it appears at all but I would like to add the number of times it appears. At the moment it prints out this -

i like to play tennis = 1111100000

i think football needs big changes = 1000011111

i like football football = 1100001000

How would I alter this code so it prints out the following..

i like to play tennis = 1111100000

i think football needs big changes = 1000011111

i like football football = 1100002000

public static void main(String[] args) {
List<String> sentences = new ArrayList<String>();
sentences.add("i like to play tennis");
sentences.add("i think football needs big changes");
sentences.add("i like football football");


List<String[]> bagOfWords = new ArrayList<String[]>();
for (String str : sentences) {
bagOfWords.add(str.split(" "));

}
Set<String> uniqueBagOfWords = new LinkedHashSet<String>();
for (String[] s : bagOfWords) {
for (String ss : s)
for (String st : ss.split(" "))
if (!uniqueBagOfWords.contains(st))
uniqueBagOfWords.add(st);

}



for (String s : sentences) {
StringBuilder numOfOccurences = new StringBuilder();
int count = 0;


for (String word : uniqueBagOfWords) {


if (s.contains(word)) {

numOfOccurences.append(count+1);
} else {
numOfOccurences.append("0");
}

}
System.out.println(s + " = " + numOfOccurences);


}

}

Answer

You may rewrite the last for loop like this:

for (String s : sentences) {
    StringBuilder numOfOccurences = new StringBuilder();

    for (String word : uniqueBagOfWords) {
        int count = 0;
        for (String wordFromSentence : s.split(" ")) {
            if (wordFromSentence.equals(word)) {
                count++;
            }
        }
        numOfOccurences.append(count);
    }
    System.out.println(s + " = " + numOfOccurences);

}
Comments