【发布时间】:2018-06-17 15:43:58
【问题描述】:
我有一些代码读取两个文本文件(一个包含要删除的单词,另一个包含从 Twitter 收集的数据)。在我的程序中,我在分隔符之间包含了 Twitter 用户名,以便我可以在稍后阶段删除它们(以及停用词)。
我的代码(如下)完美地从数据中删除了停用词,但我不知道如何删除两个定界符之间的字符串。我有一种感觉 indexOf() 的内置函数可能最适合它,但我不确定如何用我当前的代码来实现它。这是一个删除分隔符、推特句柄和停用词的示例测试用例:
输入:
--/--RedorDead :--/-- Tottenham are the worst team in existence
输出:
Tottenham worst team existence
我的代码:
Scanner stopWordsFile = new Scanner(new File("stopwords_twitter.txt"));
Scanner textFile = new Scanner(new File("Test.txt"));
// Create a set for the stop words (a set as it doesn't allow duplicates)
Set<String> stopWords = new HashSet<String>();
// For each word in the file
while (stopWordsFile.hasNext()) {
stopWords.add(stopWordsFile.next().trim().toLowerCase());
}
// Creates an empty list for the test.txt file
ArrayList<String> words = new ArrayList<String>();
// For each word in the file
while (textFile.hasNext()) {
words.add(textFile.next().trim().toLowerCase());
}
// Create an empty list (a list because it allows duplicates)
ArrayList<String> listOfWords = new ArrayList<String>();
// Iterate over the list "words"
for(String word : words) {
// If the word isn't a stop word, add to listOfWords list
if (!stopWords.contains(word)) {
listOfWords.add(word);
}
stopWordsFile.close();
textFile.close();
for (String str : listOfWords) {
System.out.print(str + " ");
}
【问题讨论】:
-
为什么
"are the"被删除了? -
因为它们是 stopword_twitter 文本文件中的单词,也需要删除。
-
但正如我在描述中所说,我现有的代码已经这样做了