开发者

Search a word in a text file and return its frequency

How to search for a particular word in a text file containing texts of words and 开发者_JS百科 return its frequency or occurrences ?


Using a Scanner:

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);

Output:

Word count:  2
Total count: 24
Frequency:   0.08


Read These

http://wiki.answers.com/Q/Write_a_Java_program_to_find_occurrences_of_given_word_in_a_text

http://www.devdaily.com/java/edu/pj/pj010006/

http://www.daniweb.com/forums/thread181889.html


  • Read each line in the file. See Tutorial | Reading, Writing, and Creating Files
  • You can use string.contains to check if the line contains the word you are looking for
  • increment an int counter if the word is found
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜