0

我想在文件的每一行中找到一个单词的频率。我想对文件中的每个单词都这样做。我在 java 中使用 BufferedReader 和 FileReader。

4

1 回答 1

2

我推荐两件事:

1)更好地分解你的问题。您是否正在尝试查找每行中单词的频率?或文件中单词的频率。如,如果您的输入是:

test test dog cat dog dog cat
test cat dog dog cat test

你想要:

test: 2, 1
dog: 3, 2
cat: 2, 2

或者你想要

test: 3
dog: 5
cat: 4

2)这是您需要的工具

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 */
于 2011-02-18T16:10:41.790 回答