我正在尝试“拼写检查”给定的文本文件,我的程序读取给定的文件并引用我的老师给出的字典哈希集。如果它找到一个不在字典中或被某些字符分割的词,它会用 <> 将这个词括起来。一个条件是我需要保留单词之间的空格,但我不知道如何确保程序做到这一点。
当前代码:
public static void spellCheck(File processingFile, File dictionaryFile) {
try {
HashSet<String> dictionary = new HashSet<>();
FileReader processing = new FileReader(processingFile);
FileReader dictionaryF = new FileReader(dictionaryFile);
PrintWriter outputFile = new PrintWriter("test_spellChecked.txt");
Scanner scnr = new Scanner(dictionaryF);
String word = scnr.nextLine();
while(scnr.hasNext()) {
//dont need to check for double words cus its literally a dictionary
dictionary.add(word);
word = scnr.nextLine();
}
//somehow create a stored text file of the processing text that gets changed based on the dictionary check
scnr = new Scanner(processing);
word = scnr.next();
boolean isCorrect = true;
while(scnr.hasNext()) {
if(word.matches("[a-zA-Z]+")) {
if(!dictionary.contains(word.toLowerCase())) {
outputFile.print("<" + word + ">");
}
else
outputFile.print(word);
}
else {
String[] words = word.split("((?=[^a-zA-Z])|(?<=[^a-zA-Z]))");
for(String splitWord: words) {
if(!dictionary.contains(splitWord.toLowerCase())) {
outputFile.print("<" + splitWord + ">");
}
else
outputFile.print(splitWord);
}
}
word = scnr.next();
}
outputFile.close();
System.out.println("File has been checked.");
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
我只是想出了如何用完全相同的单词将文件重写到文件中,我不确定如何保留空格。
while(scnr.hasNext()) {
if(word.matches("[a-zA-Z]+")) {
if(!dictionary.contains(word.toLowerCase())) {
outputFile.print("<" + word + ">");
}
else
outputFile.print(word);
}
else {
String[] words = word.split("((?=[^a-zA-Z])|(?<=[^a-zA-Z]))");
for(String splitWord: words) {
if(!dictionary.contains(splitWord.toLowerCase())) {
outputFile.print("<" + splitWord + ">");
}
else
outputFile.print(splitWord);
}
}
word = scnr.next();
}
这就是空间被删除的原因。
word 和 splitWord 不包含空格。
因为你正在用
scnr.next()
阅读单词
next()
读取文件直到空格或行更改。
这样改
outputFile.print(splitWord+" ");
或
outputFile.format("%s ", splitWord);
会节省空间。
但这不会保存
\n
或\t
如果你也想保存
\n
,
for(String word:words){
if(word.matches("[a-zA-Z]+")) {
if(!dictionary.contains(word.toLowerCase())) {
outputFile.print("<" + word + ">");
}
else
outputFile.print(word);
}
else {
String[] words = word.split("((?=[^a-zA-Z])|(?<=[^a-zA-Z]))");
for(String splitWord: words) {
if(!dictionary.contains(splitWord.toLowerCase())) {
outputFile.print("<" + splitWord + ">");
}
else
outputFile.print(splitWord);
}
}
outputFile.println();
}
nextLine = scnr.nextLine();
words = nextLine.split(" ");
}