import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Test {
List<String> knownWordsArrayList = new ArrayList<String>();
List<String> wordsArrayList = new ArrayList<String>();
public void readKnownWordsFile()
{
try {
FileInputStream fstream2 = new FileInputStream("knownWords.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fstream2));
String strLine;
while ((strLine = br2.readLine()) != null) {
knownWordsArrayList.add(strLine);
}
} catch (Exception e) {
}
}
public void readFile() {
try {
FileInputStream fstream = new FileInputStream("newWords.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String numberedLineRemoved = "";
String strippedInput = "";
String[] words;
String trimmedString = "";
while ((strLine = br.readLine()) != null) {
numberedLineRemoved = numberedLine(strLine);
strippedInput = numberedLineRemoved.replaceAll("\\p{Punct}", "");
if ((strippedInput.trim().length() != 0) || (!strippedInput.contains("")) || (strippedInput.contains(" "))) {
words = strippedInput.split("\\s+");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().length() != 0) {
wordsArrayList.add(words[i]);
}
}
}
}
for (int i = 0; i < knownWordsArrayList.size(); i++) {
wordsArrayList.add(knownWordsArrayList.get(i));
}
HashSet h = new HashSet(wordsArrayList);
wordsArrayList.clear();
wordsArrayList.addAll(h);
for (int i = 0; i < wordsArrayList.size(); i++) {
System.out.println(wordsArrayList.get(i));
}
System.out.println(wordsArrayList.size());
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public String numberedLine(String string) {
if (string.matches(".*\\d.*")) {
return "";
} else {
return string;
}
}
public static void main(String[] args) {
Test test = new Test();
test.readKnownWordsFile();
test.readFile();
}
}
从文件添加到 knownWordsArrayList。然后我转到另一个文件并将单词放入 wordsArrayList。然后我制作了一个 hashSet 来删除重复的单词,但它们仍然存在。例如,“Mrs”在 knownWordsArrayList 中,但是当我打印 wordsArrayList 时,我仍然看到“Mrs”。我不明白为什么没有删除重复的单词。会不会跟字符集有关?