我正在尝试阅读诗篇txt文件(具有拼写错误)的内容,并将其与字典进行比较以过滤这些错误。我最终希望程序打印出包含拼写错误的txt文件的所有元素。我遇到了嵌套for循环的问题,因为我不确定如何遍历我的字典txt文件中的每个字符串并将其与我的诗txt文件进行比较。
public static String compareFileContents(String poem, String dictionary)
throws FileNotFoundException, IOException{
char[] buffer = null;
try {
BufferedReader br1 = new BufferedReader(new java.io.FileReader(poem));
int bufferLength = (int)(new File(poem).length());
buffer = new char[bufferLength];
br1.read(buffer, 0, bufferLength);
br1.close();
} catch(IOException e) {
System.out.println(e.toString());
}
String text = new String(buffer);
String[] poem2 = text.split(" ");
char[] buffer2 = null;
try {
BufferedReader br2 = new BufferedReader(new java.io.FileReader(dictionary));
int bufferLength = (int)(new File(dictionary).length());
buffer2 = new char[bufferLength];
br2.read(buffer2, 0, bufferLength);
br2.close();
} catch(IOException e) {
System.out.println(e.toString());
}
String dictionary2 = new String(buffer);
String[] dictionary3 = dictionary2.split(" ");
boolean found=false;
for(int i=0;i<dictionary3.length;i++){
for(int j=0;j<poem2.length;j++) {
if(!poem2[j].equals(dictionary3[i])) {
System.out.println(poem2[j]);
}
}
}
答案 0 :(得分:0)
你有正确的想法,你只是颠倒你的嵌套循环。你想首先遍历诗中的每个单词。然后,对于诗的每个单词,循环遍历字典中的每个单词。如果找到匹配项,请继续。如果你在没有找到当前诗词的匹配的情况下遍历整个字典,你就会发现拼写错误。你可以像这样实现它。
您还会使用不正确的分隔符进行拆分。由于您的诗词由空格和换行符分隔,您应该使用正则表达式按空格分割。同样,由于你的字典单词被换行符分割,你应该按换行符分开。
// ...
String[] poem2 = text.split("\\s+");
// ...
String[] dictionary3 = dictionary2.split("\n");
for(int i = 0; i < poem2.length; i++) {
boolean found = false;
for(int j = 0; j < dictionary3.length; j++) {
if(poem2[i].equals(dictionary3[j])) {
found = true;
break;
}
}
if(!found) {
System.out.println(poem2[i]);
}
}
答案 1 :(得分:0)
这是一个较晚的答案,它基于为检查TextArea中的拼写而编写的拼写检查器
可以下载字典HERE words_alpha.txt的作品
这是用JavaFX 8用Netbeans 8.2编写的
主班
public class SpellChecker extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("spellchecker.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("spellchecker.css").toExternalForm());
root.getStyleClass().add("pane");// Code to style Anchor Pane's in CSS
stage.setScene(scene);
stage.getIcons().add(new Image("Images/s.bmp"));// All Stages have this icon
stage.setTitle("Spell Checker");
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
public class SpellCheckerController implements Initializable {
@FXML Pane spellcheckerPane;
@FXML TextArea txaInput;
@FXML TextField txtMessage,txtReplacementWord,txtWordToReplace;
@FXML ComboBox cboMisspelledWord,cboCorrectSpelling;
@FXML Button btnClose,btnCheckSpelling,btnIgnore,btnReplace;
ArrayList<String> dictionary = new ArrayList<>();
ArrayList<String> capture = new ArrayList<>();
String[] strArray;
String searchString;
StringBuilder sb;
String strSF;
String middleChar;
String strEntered;
private void populate(){
txaInput.setText("Tak the Tz short-term bul buy the hor sve's and see if thi will be cau\n\nNew Laaz abo");
}
private void SpellCheck(){
txtMessage.setText("Search Complete");
cboMisspelledWord.getItems().clear();
String line = txaInput.getText();
line = line.replaceAll("[=@#$%&()+,!.?<>:|_*;0-9]","");
strArray = line.split("\\s");
for(int X = 0; X < strArray.length;X++){
strEntered = strArray[X];
boolean found = false;
for(int Y = 0; Y < dictionary.size();Y++){
if(dictionary.get(Y).equalsIgnoreCase(strEntered)){
found = true;
}
}if(found != false){
capture.add(strEntered);
}
}
for(int P = 0; P < capture.size();P++){
String gotIT = capture.get(P);
String[] EMPTY_STRING_ARRAY = new String[0];
List<String> list = new ArrayList<>();
Collections.addAll(list, strArray);
list.removeAll(Arrays.asList(gotIT));
strArray = list.toArray(EMPTY_STRING_ARRAY);
// Code above removes the correct spelled words from ArrayList capture
// Leaving the misspelled words in strArray then below they are added
// to the cboMisspelledWord which then holds all the misspelled words
}
for(int r = 0; r < strArray.length;r++){
String A = strArray[r];
cboMisspelledWord.getItems().add(A);
}
if(cboMisspelledWord.getItems().isEmpty()){
txtMessage.setText("No Misspelled Words");
}else{
int n = strArray.length;
txtMessage.setText("There are "+n+" Misspelled Words");
}
}
public void cboCorrectSpelling(){
ObservableList spell = FXCollections.observableArrayList();
spell.removeListener((InvalidationListener) cboCorrectSpelling);
}
@FXML
private void getCorrectSpelling(){
if(cboCorrectSpelling.getValue() != null) {
String selected = cboCorrectSpelling.getValue().toString();
txtReplacementWord.setText(selected);
String testCB = txtWordToReplace.getText();
boolean isCAP;
char firstChar = testCB.charAt(0);
if (Character.isUpperCase(firstChar)) {
isCAP = true;
String MakeCapital = selected;
String firstLetter = MakeCapital.substring(0,1).toUpperCase();
String restLetters = MakeCapital.substring(1).toLowerCase();
txtReplacementWord.setText(firstLetter+restLetters);
}
btnReplace.requestFocus();
btnReplace.setStyle("-fx-text-fill:red;");
txtMessage.setText("Click Mouse to Replace");
}
}
public void cboMisspelledWord(){
ObservableList misspell = FXCollections.observableArrayList();
}
@FXML
private void getMisspelledWord(){
if(cboMisspelledWord.getValue() != null) {
String selected = cboMisspelledWord.getValue().toString();
txtWordToReplace.setText(selected);
if(selected.contains("\"")|| selected.contains("-")|| selected.contains("'")){
txtMessage.setText("Manually Replace or Ignore");
txtReplacementWord.requestFocus();
return;
}
}
cboCorrectSpelling.requestFocus();
FindCorrectSpelling();
}
private void FindCorrectSpelling(){
if(txtWordToReplace.getText().isEmpty()){
txtMessage.setText("Select Misspelled Word");
return;
}
searchString = txtWordToReplace.getText();
for(int indexSC = 0; indexSC < dictionary.size();indexSC++){
String NewSS = txtWordToReplace.getText().toLowerCase();
int a = NewSS.length();
if(a < 2){
txtMessage.setText("Word NOT in Dictionary");
return;
}
int Z;
if(a == 2){// manage CR was 0
Z = 2;// was 0
}else if(a == 3){
Z = 3;
}else if(a > 3 && a < 5){
Z = 4;
}else if(a >= 5 && a < 8){
Z = 4;
}else{
Z = 5;
}
txtMessage.setText("");
String strS = searchString.substring(0,Z).toLowerCase();
strSF = strS;
ArrayList<String> list = new ArrayList<>();
int W = txtWordToReplace.getText().length();
String frontChar = txtWordToReplace.getText().substring(0, 1).toLowerCase();
String endChar = txtWordToReplace.getText().substring(W - 2, W);
if(W > 7){
middleChar = txtWordToReplace.getText().substring(W-5, W);
}else{
middleChar = txtWordToReplace.getText().substring(W-1, W);
}
dictionary.stream().filter(s -> s.startsWith(strSF)
|| s.startsWith(frontChar, 0)
&& s.length() > 1 && s.length() <= W+3
&& s.endsWith(endChar)
&& s.startsWith(frontChar)
&& s.contains(middleChar))
.forEach(list :: add);
for(int X = 0; X < list.size();X++){
String strA = (String) list.get(X);
sort(list);
cboCorrectSpelling.getItems().add(strA);
}
break;
}
}
@FXML
private void onClick(){
onReplace();
}
@FXML
private void onPress(KeyEvent ev) throws IOException{
KeyCode kc = ev.getCode();
if(kc == KeyCode.ENTER){
onReplace();
}
}
@FXML
private void onReplace(){
if(txtReplacementWord.getText().isEmpty() || txtWordToReplace.getText().length() == 0){
txtMessage.setText("Enter the Replacement Word");
return;
}
if(txtReplacementWord.getText().length() >= 1){
String fL = txtReplacementWord.getText().substring(0, 1);
if(fL.contains(" ")){
txtMessage.setText("No Leading Spaces");
return;
}
}
if(txtWordToReplace.getText().length() >= 1){
String fL = txtWordToReplace.getText().substring(0, 1);
if(fL.contains(" ")){
txtMessage.setText("No Leading Spaces HERE");
return;
}
}
Map<String, String> replacements = new HashMap<>();
replacements.put(txtWordToReplace.getText(), txtReplacementWord.getText());
Pattern pattern = Pattern.compile("\\S+");
String text = txaInput.getText();
sb = new StringBuilder();
Matcher matcher = pattern.matcher(text);
int lastEnd = 0;
while (matcher.find()) {
int startIndex = matcher.start();
if (startIndex > lastEnd) {
sb.append(text.substring(lastEnd, startIndex));
}
String group = matcher.group();
String result = replacements.get(group);
sb.append(result == null ? group : result);
lastEnd = matcher.end();
}
sb.append(text.substring(lastEnd));
txaInput.setText(sb.toString());
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
txtMessage.setText("");
txtReplacementWord.setText("");
txtWordToReplace.setText("");
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.requestFocus();
btnReplace.setStyle("-fx-text-fill:black;");
if(cboMisspelledWord.getItems().isEmpty()){
onCheckSpelling();
}
}
@FXML
private void onIgnore(){
if(cboMisspelledWord.getItems().isEmpty() || txtWordToReplace.getText().length() == 0 || txtWordToReplace.getText().contains(" ")){
txtMessage.setText("Nothing to Ignore");
return;
}
cboMisspelledWord.getItems().remove(txtWordToReplace.getText());
txtWordToReplace.setText("");
txtReplacementWord.setText("");
cboMisspelledWord.requestFocus();
cboCorrectSpelling.getItems().clear();
if(cboMisspelledWord.getItems().isEmpty()){
onCheckSpelling();
}
}
@FXML
private void onCheckSpelling(){
String line = txaInput.getText();
if(line.length() == 0){
txtMessage.setText("No Data Entered");
return;
}
txtWordToReplace.setText("");
txtReplacementWord.setText("");
cboMisspelledWord.requestFocus();
cboCorrectSpelling.getItems().clear();
cboMisspelledWord.getItems().clear();
SpellCheck();
}
@FXML
private void onClose(){
System.exit(0);
Platform.exit();
}
private void onLoad() throws FileNotFoundException, IOException{
long start2 = System.nanoTime();
Instant namesStart = Instant.now();
try (BufferedReader input = new BufferedReader(new FileReader("C:/A_WORDS/dictionary.txt"))) {
for(String line = input.readLine();
line != null;
line = input.readLine()) {
dictionary.add(line);
}
input.close();
}
int gl = dictionary.size();
System.out.println("## gl "+gl);
for(int X = 0; X < dictionary.size();X++){
String D = dictionary.get(X);
//System.out.println("#### Dictionary "+D);
if(X == gl-1){
long time2 = System.nanoTime() - start2;
System.out.println("!!!!! time2 "+time2/1000000);
txtMessage.setText("Loaded in "+time2/1000000+" ms");
Instant namesEnd = Instant.now();
long timeElapsedNames = Duration.between(namesStart, namesEnd).toMillis();
System.out.println("Name time: " + timeElapsedNames + "ms");
}
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
spellcheckerPane.getStyleClass().add("pane");
populate();
try {
onLoad();
} catch (IOException ex) {
Logger.getLogger(SpellCheckerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane id="AnchorPane" fx:id="spellcheckerPane" onMouseClicked="#onClick" prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SpellChecker.SpellCheckerController">
<children>
<TextArea fx:id="txaInput" focusTraversable="false" layoutX="44.0" layoutY="28.0" prefHeight="150.0" prefWidth="720.0" wrapText="true">
<font>
<Font name="System Bold" size="18.0" />
</font></TextArea>
<TextField fx:id="txtWordToReplace" focusTraversable="false" layoutX="44.0" layoutY="254.0">
<font>
<Font name="System Bold" size="18.0" />
</font>
</TextField>
<TextField fx:id="txtReplacementWord" focusTraversable="false" layoutX="44.0" layoutY="349.0">
<font>
<Font name="System Bold" size="18.0" />
</font>
</TextField>
<TextField fx:id="txtMessage" focusTraversable="false" layoutX="44.0" layoutY="433.0" prefWidth="320.0">
<font>
<Font name="System Bold" size="18.0" />
</font>
</TextField>
<ComboBox fx:id="cboMisspelledWord" focusTraversable="false" layoutX="550.0" layoutY="219.0" onAction="#getMisspelledWord" prefWidth="215.0" visibleRowCount="5" />
<ComboBox fx:id="cboCorrectSpelling" focusTraversable="false" layoutX="550.0" layoutY="286.0" onAction="#getCorrectSpelling" prefWidth="215.0" />
<Button fx:id="btnClose" focusTraversable="false" layoutX="50.0" layoutY="510.0" mnemonicParsing="false" onAction="#onClose" text="CLOSE">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Button>
<Button fx:id="btnCheckSpelling" layoutX="482.0" layoutY="510.0" mnemonicParsing="false" onAction="#onCheckSpelling" text="CheckSpelling">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Button>
<Button fx:id="btnIgnore" focusTraversable="false" layoutX="361.0" layoutY="510.0" mnemonicParsing="false" onAction="#onIgnore" text="Ignore">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Button>
<Button fx:id="btnReplace" focusTraversable="false" layoutX="660.0" layoutY="510.0" mnemonicParsing="false" onAction="#onReplace" onKeyPressed="#onPress" text="Replace">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Button>
<Label focusTraversable="false" layoutX="47.0" layoutY="316.0" text="Replacement Word">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Label>
<Label focusTraversable="false" layoutX="45.0" layoutY="222.0" text="Word to Replace">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Label>
<Label focusTraversable="false" layoutX="45.0" layoutY="401.0" text="Messages">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Label>
<Label focusTraversable="false" layoutX="380.0" layoutY="222.0" text="Misspelled Words">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Label>
<Label focusTraversable="false" layoutX="393.0" layoutY="289.0" text="Correct Spelling">
<font>
<Font name="System Bold" size="18.0" />
</font>
</Label>
</children>
</AnchorPane>