I want to find the frequency of a word in each line of a file. I want to do this for every word in the开发者_运维知识库 file. I'm using BufferedReader and FileReader in java.
I recommend two things:
1) break down your question better. Are you trying to find the frequency of words in each line? Or the frequency of words in the file. As in, if your input was :
test test dog cat dog dog cat
test cat dog dog cat test
Would you want:
test: 2, 1
dog: 3, 2
cat: 2, 2
Or would you want
test: 3
dog: 5
cat: 4
2) here's the tools you need
Map<String,Integer> wordCounts; // store your word counts in your class
/**
* countWord- a method to signify counting a word
* @param word the word just counted
*/
public void countWord(String word) {
int counts = 0; // assume it does not exist yet
if(wordCounts.containsKey(word)) { // but if it does, get that count
counts = wordCounts.get(word);
} /* end if(contains(word))*/
wordCounts.put(word,counts + 1); // tell the map to put one more than there was
} /* end countWord */
精彩评论