搜索文本文件中的单词并返回其频率

时间:2011-02-24 08:20:56

标签: java

如何在包含单词文本的文本文件中搜索特定单词并返回其频率或出现次数?

3 个答案:

答案 0 :(得分:5)

使用扫描仪:

String text = "Question : how to search for a particular word in a " +
        "text file containing texts of words and return its " +
        "frequency or occurrences ?";

String word = "a";

int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(text);
while (s.hasNext()) {
    totalCount++;
    if (s.next().equals(word)) wordCount++;
}

System.out.println("Word count:  " + wordCount);
System.out.println("Total count: " + totalCount);
System.out.printf("Frequency:   %.2f", (double) wordCount / totalCount);

输出:

Word count:  2
Total count: 24
Frequency:   0.08

答案 1 :(得分:0)

答案 2 :(得分:0)