假设我有这个单词列表:
String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};
比我有文字
String text = "I would like to do a nice novel about nature AND people"
是否有匹配停止词并在忽略大小写的情况下删除它们的方法?像这样的地方吗?:
String noStopWordsText = remove(text, stopWords);
结果:
" would like do nice novel nature people"
如果您知道正则表达式,那会很好用,但我真的更喜欢像通用解决方案这样更注重性能的解决方案。
顺便说一句,现在我正在使用这种缺乏适当的不区分大小写处理的公共(public)方法:
private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};
noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);
最佳答案
用停用词创建一个正则表达式,使其不区分大小写,然后使用匹配器的 replaceAll
方法将所有匹配项替换为空字符串
import java.util.regex.*;
Pattern stopWords = Pattern.compile("\\b(?:i|a|and|about|an|are|...)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher matcher = stopWords.matcher("I would like to do a nice novel about nature AND people");
String clean = matcher.replaceAll("");
pattern中的...
是我偷懒,继续停用词列表。
另一种方法是遍历所有停用词并使用String
的replaceAll
方法。该方法的问题是 replaceAll
将为每次调用编译一个新的正则表达式,因此在循环中使用效率不高。此外,当您使用 String
的 replaceAll
时,您不能传递使正则表达式不区分大小写的标志。
编辑:我在模式周围添加了 \b
以使其只匹配整个单词。我还添加了 \s*
以使其包含所有空格,这可能不是必需的。
关于java - 从java中的另一个字符串中删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4769282/