从字符串中删除所有非单词字符(标点符号)

3

好的,这是我第一次发帖,如果有任何错误请见谅。简而言之,我得到了一个字符串数组,我的目标是计算字符串中唯一单词的数量,并从数组中删除任何标点符号。

public static HashMap<String, Integer> uniqueWords(String[] book) {
    HashMap<String, Integer> hm = new HashMap<>();

    for (int i = 0; i < book.length; i++) {
        if (hm.containsKey(book[i])) {
            hm.put(book[i], hm.get(book[i]) + 1);
        } else {
            book[i] = book[i].replaceAll("[^a-zA-Z]","").replaceAll("\\p{Punct}","").replaceAll("\\W+","").replaceAll("\\n","").toLowerCase();
            hm.put(book[i], 1);
        }
    }
    return hm;
}

输入: {"Redfish", "redfish", "redfish", "Bluefish", "bluefish", "bluefish", "*", "%", ""};

输出: {=2, bluefish=3, redfish=3}

所以我已经成功地去除了任何空格,但仍然计算星号和百分比符号。

如果有帮助,请谢谢。

1个回答

0
尝试一些类似这样的东西--
    public static HashMap<String, Integer> uniqueWords(String[] book) {
    HashMap<String, Integer> hm = new HashMap<>();
string strBook = "";
int key = 1;
    for (int i = 0; i < book.length; i++) {
    strBook= book[i].replaceAll("[^a-zA-Z]","").replaceAll("\\p{Punct}","").replaceAll("\\W+","").replaceAll("\\n","").toLowerCase();
        if (!hm.containsKey(strBook)) {
            hm.put(key, strBook);
            key++;
        }
    }
    return hm;
}

我尝试了一些变化,但都没有成功,无论如何感谢您的解决方案。 - Camilo Riviere
我意识到了我的错误。很少情况下,如果一个非单词字符没有附加在包含单词的字符串上,那么我的代码将会移除这个非单词字符。 - Camilo Riviere
以下是代码的最终版本:public static HashMap<String, Integer> uniqueWords(String[] book) {HashMap hm = new HashMap<>(); for (int i = 0; i < book.length; i++) { book[i] = removePunctuation(book[i]); if(!hm.containsKey(book[i])) hm.put(book[i], 1); else hm.put(book[i], hm.get(book[i]) + 1); } return hm;}public static String removePunctuation(String book){ for (int i = 0; i < book.length(); i++) book = book.replaceAll("[^a-zA-Z]", "").toLowerCase();return book;} - Camilo Riviere
很好,很高兴你解决了这个问题。 - pizzaslice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接