【发布时间】:2019-07-02 11:55:12
【问题描述】:
我正在尝试制作一个拼写检查应用程序。我的代码的工作原理是它能够检测何时存在拼写错误,我通过使用包含大量单词的文本文件来比较用户输入的正确/错误拼写来完成此操作。问题是我正在尝试实现一种方法来给出错误拼写的建议,而不是仅仅说明拼写不正确。
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
final String theDictionary = "dictionary.txt";
String[] words = dictionary(theDictionary);
boolean correctSpelling = checking(words, userWord);
if (!correctSpelling) {
System.out.println("Incorrect spelling");
}
else {
System.out.println("The spelling is correct");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException {
final String fileName = "dictionary.txt";
int dictionaryLength = 0, i = 0;
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
++dictionaryLength;
dictionary.nextLine();
}
}
String[] theWords = new String[dictionaryLength];
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords[i] = dictionary.nextLine();
i++;
}
}
return theWords;
}
public static boolean checking(String[] dictionary, String userWord) {
for ( int i =0; i < dictionary.length; i++) {
if (userWord.equals(dictionary[i])) {
return true;
}
}
return false;
}
}
总的来说,我对它可以检测到拼写错误的结果感到满意,但有没有办法在拼写错误时向用户输入提供建议。先感谢您。
【问题讨论】:
-
您可以很容易地在系统中写出单词拼写错误。并打印出单词?在您的示例中,我想只是在检查中返回单词,以便您可以打印出来?从检查中,如果它不正确,只需返回单词?
-
您要解决的问题非常困难,即使是 Microsoft Office 中的拼写检查器也不能 100% 正确。还要考虑到,字典中存在一个单词并不意味着它就是作者想要的。
-
@cathy liam 阅读norvig.com/spell-correct.html 以实现基本的拼写校正器。这篇文章有几乎所有著名语言的代码。这篇文章是彼得·诺维格的经典著作之一。
标签: java spell-checking