我正在尝试做一个练习,在该练习中,我需要创建一个类以读取.txt中的单词,然后将这些单词放入HashSet中。问题是,如果文本显示为“我是丹尼尔,我是丹尼尔”。我会用一个词来表示“上午”,“上午”。和“丹尼尔”和“丹尼尔”。我该如何解决?
这是我的代码。 (我尝试使用正则表达式,但出现异常):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
try {
File file = new File(args[0]);
HashSet<String> set = readFromFile(file);
set.forEach(word -> System.out.println(word));
}
catch(FileNotFoundException e) {
System.err.println("File Not Found!");
}
}
private static HashSet<String> readFromFile(File file) throws FileNotFoundException {
HashSet<String> set = new HashSet<String>();
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String s = scanner.next("[a-zA-Z]");
set.add(s.toUpperCase());
}
scanner.close();
return set;
}
}
[扫描程序尝试读取与正则表达式不匹配的字符串时引发错误。
String s = scanner.next("[a-zA-Z]");
而不是在扫描程序中传递正则表达式。读取单词并删除特殊字符,如下所示。
String s = scanner.next();
s = s.replaceAll("[^a-zA-Z]", "");