Wai Loon II
Wai Loon II

Reputation: 259

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 return its frequency or occurrences ?

Upvotes: 3

Views: 12897

Answers (3)

aioobe
aioobe

Reputation: 421020

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

Upvotes: 7

dogbane
dogbane

Reputation: 274612

Upvotes: 0

Related Questions