【问题标题】:Stop words not being correctly removed from string停用词未从字符串中正确删除
【发布时间】:2017-05-17 03:05:35
【问题描述】:

我有一个函数可以从文件中读取停用词并将其保存在 HashSet 中。

HashSet<String> hset = readFile();

这是我的字符串

String words = "the plan crash is invisible";

我正在尝试从字符串中删除所有停用词,但它无法正常工作

我得到的输出:计划崩溃不可见

我想要的输出 => 计划崩溃不可见

代码:

HashSet<String> hset = readFile();
        String words = "the plan crash is invisible";

        String s = words.toLowerCase();

        String[] split = s.split(" ");
        for(String str: split){
            if (hset.contains(str)) {

                s = s.replace(str, "");

            } else {

            }

        }

        System.out.println("\n" + "\n" + s);

【问题讨论】:

  • 尝试使用 equals() 或 equalsIgnoreCase()
  • 而且您不应该使用replace,因为当您尝试删除整个单词“is”时,它会删除不可见的“is”。或者至少你应该改变你使用它的方式,以确保它只删除整个单词。

标签: java replace stop-words


【解决方案1】:

虽然hset.contains(str) 匹配完整单词,但s.replace(str, ""); 可以替换作为输入String 单词一部分的“停止”单词的出现。因此,“invisible”变成了“invible”。

由于您无论如何都要遍历s 的所有单词,因此您可以构造一个包含Set 中未包含的所有单词的String

StringBuilder sb = new StringBuilder();
for(String str: split){
    if (!hset.contains(str)) {
        if (sb.length() > 0) {
            sb.append(' ');
        }
        sb.append(str);
    }
}
System.out.println("\n" + "\n" + sb.toString());

【讨论】:

  • @litelite 现已修复
【解决方案2】:

无需检查您的字符串是否包含停用词或拆分您的字符串,您可以使用使用正则表达式的replaceAll,如下所示:

for (String str : hset) {
    s = s.replaceAll("\\s" + str + "|" + str + "\\s", " ");
}

示例:

HashSet<String> hset = new HashSet<>();
hset.add("is");
hset.add("the");

String words = "the plan crash is invisible";

String s = words.toLowerCase();

for (String str : hset) {
    s = s.replaceAll("\\s" + str + "|" + str + "\\s", " ");
}
s = s.replaceAll("\\s+", " ").trim();//comment and idea of @davidxxx
System.out.println(s);

这可以给你:

plan crash invisible

【讨论】:

  • 这个想法很有趣,但我认为可能在之前或之后以及多个空格处理更难用正则表达式处理。例如,在您的情况下,您有一个输出中不需要的空格
  • 谢谢@davidxxx 是的,这是正确的,我想我现在需要使用trim()replaceAll("\\s+", " ") 看看我的答案:) 谢谢你
猜你喜欢
  • 1970-01-01
  • 2013-12-16
  • 2014-05-22
  • 1970-01-01
  • 2014-06-06
  • 2015-02-25
  • 2019-12-18
  • 2016-10-06
相关资源
最近更新 更多