【问题标题】:Removing strings between two delimiters删除两个分隔符之间的字符串
【发布时间】: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 文本文件中的单词,也需要删除。
  • 但正如我在描述中所说,我现有的代码已经这样做了

标签: java delimiter


【解决方案1】:

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

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

表达式*? 是一个不情愿 量词,这意味着它在匹配的同时尽可能地匹配little,这反过来意味着它将在下一个分隔符处停止如果输入中有多个分隔符对,则在第一个之后。

我在末尾添加了\s*,以便在结束分隔符之后删除尾随空格(您的示例似乎暗示需要)。


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

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

【讨论】:

  • 这不仅删除了分隔符,还删除了它们之间的文本?
  • @Bean 根据问题删除:分隔符和之间的所有内容
  • 啊,我明白了!我会把它放在代码底部的for循环中吗?
【解决方案2】:
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

【讨论】:

    最近更新 更多