我有一个函数,它从文件中读取停用词并将其保存在HashSet中。
HashSet<String> hset = readFile();
这是我的字符串
String words = "the plan crash is invisible";
我正在尝试从字符串中删除所有停用词,但它无法正常工作
我得到的输出:计划崩溃无法
输出我想=&gt; 计划崩溃隐形
代码:
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);
答案 0 :(得分:3)
虽然hset.contains(str)
匹配完整字词,s.replace(str, "");
可以替换输入String
字词的“停止”字词的出现次数。因此,“inv ible”变为“不可见”。
由于您正在迭代s
的所有字词,因此您可以构建一个String
,其中包含Set
中未包含的所有字词:
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());
答案 1 :(得分:1)
无需检查您的字符串是否包含停用词或拆分字符串,您可以使用使用正则表达式的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