【发布时间】:2023-03-23 16:14:01
【问题描述】:
我想从一个大的文本文件中实现一个字符串匹配的任务。 1.替换所有非字母数字字符 2.统计文本文件中特定词条的数量。例如,匹配词“tom”。匹配不区分大小写。所以我应该算上“汤姆”这个词。但是不应该计算明天这个词。
code template one:
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile));
} catch (FileNotFoundException e1) {
System.out.println("Not found the text file: "+inputFile);
}
Scanner scanner = null;
try {
while (( line = in.readLine())!=null){
String newline=line.replaceAll("[^a-zA-Z0-9\\s]", " ").toLowerCase();
scanner = new Scanner(newline);
while (scanner.hasNext()){
String term = scanner.next();
if (term.equalsIgnoreCase(args[1]))
countstr++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
code template two:
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile));
} catch (FileNotFoundException e1) {
System.out.println("Not found the text file: "+inputFile);
}
Scanner scanner = null;
try {
while (( line = in.readLine())!=null){
String newline=line.replaceAll("[^a-zA-Z0-9\\s]", " ").toLowerCase();
String[] strArray=newline.split(" ");//split by blank space
for (int =0;i<strArray.length;i++)
if (strArray[i].equalsIgnoreCase(args[1]))
countstr++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
通过运行这两个代码,我得到了不同的结果,Scanner 似乎得到了正确的一个。但是对于大文本文件,Scanner 的运行速度比后者慢得多。谁能告诉我原因并给出更有效的解决方案。
【问题讨论】: