簡體   English   中英

停止詞未從字符串中正確刪除

[英]Stop words not being correctly removed from string

我有一個功能,可以從文件中讀取停用詞並將其保存在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);

盡管hset.contains(str)匹配完整單詞,但s.replace(str, ""); 可以替換出現在輸入String單詞中的“ stop”單詞。 因此, “INV IBLE”變成“invible”。

由於無論如何都要遍歷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());

不需要,因此請檢查您的字符串是否包含停用詞或拆分字符串,可以使用使用正則表達式的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM