Reputation:
I'm trying to find the number of times the word "the" appears in a txt file. With the code below, I keep getting the 0 as my output when it should be 4520. I'm using the delimiter to separate "the", but it doesn't seem to count it at all. The delimiter worked when I counted all words using "[^a-zA-Z]+"
.
in.useDelimiter("[^the]+");
while (in.hasNext()) {
String words = in.next();
words = words.toLowerCase();
wordCount++;
}
System.out.println("The total number of 'the' is " + theWord);
Upvotes: 1
Views: 474
Reputation: 79015
Use \\b(?i)(the)\\b
as the regex where \\b
stands for the word boundary, i
stands for case insensitive and (the)
is for the
as a whole. Note that []
checks for individual characters enclosed by it, not for the enclosed text as a whole.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = null;
try {
in = new Scanner(new File("file.txt"));
int wordCount = 0, len;
while (in.hasNextLine()) {
len = in.nextLine().split("\\b(?i)(the)\\b").length;
wordCount = len == 0 ? wordCount + 1 : wordCount + len - 1;
}
in.close();
System.out.println("The total number of 'the' is " + wordCount);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
The total number of 'the' is 5
Content of file.txt:
The cat jumped over the rat.
The is written as THE in capital letter.
He gave them the sword.
Upvotes: 1
Reputation: 159086
In Java 9+, you can count the number of times a word occurs in a text file as follows:
static long countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).flatMap(s -> p.matcher(s).results()).count();
}
Test
System.out.println(countWord("test.txt", "the"));
test.txt
The quick brown fox
jumps over the lazy dog
Output
2
Java 8 version:
static int countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).mapToInt(s -> {
int count = 0;
for (Matcher m = p.matcher(s); m.find(); )
count++;
return count;
}).sum();
}
Java 7 version:
static int countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
int count = 0;
try (BufferedReader in = Files.newBufferedReader(Paths.get(filename), StandardCharsets.UTF_8)) {
for (String line; (line = in.readLine()) != null; )
for (Matcher m = p.matcher(line); m.find(); )
count++;
}
return count;
}
UPDATE
Full code for a Java 7+ version, without use of a method, and using the much slower Scanner
, since OP seems to have trouble copy/pasting the methods above into their code.
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
int count = 0;
try (Scanner in = new Scanner(new File("test.txt"))) {
Pattern p = Pattern.compile("\\bthe\\b", Pattern.CASE_INSENSITIVE);
while (in.hasNextLine())
for (Matcher m = p.matcher(in.nextLine()); m.find(); )
count++;
}
System.out.println("The total number of 'the' is " + count);
}
}
For comparison, the full version using the first method in this answer would be:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("The total number of 'the' is " + countWord("test.txt", "the"));
}
static long countWord(String filename, String word) throws IOException {
Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b", Pattern.CASE_INSENSITIVE);
return Files.lines(Paths.get(filename)).flatMap(s -> p.matcher(s).results()).count();
}
}
Upvotes: 3