删除两个分隔符之间的字符串

Removing strings between two delimiters

我有一些代码可以读取两个文本文件(一个包含要删除的单词,另一个包含从 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 + " ");
    }

使用正则表达式替换不情愿的量词:

str = str.replaceAll("--/--.*?--/--\s*", "");

表达式*?是一个reluctant量词,这意味着它在仍然匹配的同时尽可能匹配little,这反过来意味着它将在第一个分隔符之后的下一个分隔符处停止,以防输入中有多个分隔符对。

我在末尾添加了 \s* 以删除结束定界符后的尾随空格(您的示例似乎表明这是需要的)。


要使用这种方法,您将不得不一次读取文本文件 line,而不是 word一次,处理该行以删除用户名,然后拆分为单词:

while (textFile.hasNextLine()) {
    for (string word : textFile.nextLine().trim().toLowerCase().replaceAll("--/--.*?--/--\s*", "").split("\s+")) {
        words.add(word);
    }
}
public static String remove(String str) {
    return str.replaceAll("\s*--\/-.*?)--\/--", "").trim();
}

输入: "--/--RedorDead :--/-- Tottenham are the worst team in existence --/--RedorDead :--/-- Tottenham are the worst team in existence"

输出: "Tottenham are the worst team in existence Tottenham are the worst team in existence"

Demo at regex101.com