【问题标题】:how to get most frequent words.from given string? [closed]如何从给定的字符串中获取最频繁的单词? [关闭]
【发布时间】:2021-02-18 03:18:27
【问题描述】:

我对 java 比较陌生。我正在自己学习如何使用哈希图,我提出了一个关于如何在字符串中查找前三个单词的问题,但问题是删除字符串中的标点符号 - 双空格,逗号......当前代码仅适用对于 split() 函数所在的一个空间。

    public static void main(String[] args) {
        String s="a a a  b  c c  d d d d  e e e e e";
        int max=0;
        String maxs="";
        List<String> three= new ArrayList<String>();
        HashMap<String, Integer > top= new HashMap<String, Integer> ();
        for(String i : s.split(" ")){
            if(top.containsKey(i)) {
                top.replace(i,top.get(i)+1);
            }
            else {
                top.put(i,1);
            }
        }
      for(int i=0; i<=2;i++) {
        max=0;
        maxs="";
            for(String j: top.keySet()) { //string(word):all the values together
              if(top.get(j)> max ) {
                max=top.get(j);
                maxs=j;
              }
              
            }
              three.add(maxs);
              top.remove(maxs);
        }    
}
}

}

最常用的词?

【问题讨论】:

  • 还有另一个问题,如果我想删除所有标点符号,但不删除与单词相关的标点符号,例如不会 - 在这里我不想删除 ' 如果它不会 ' 那么我希望它被删除。 ?
  • 答案好像被删除了,如果你把它加回来我可以检查它是否有效。
  • 您在问 2 个问题:1) 如何去除单词中的标点符号,以及 2) 如何获取最常用的单词。请编辑您的问题以将其缩小为 1 个问题,并删除所有并非直接用于演示问题的代码。

标签: java regex string for-loop


【解决方案1】:

...问题是删除字符串中的标点符号-双空格, 逗号...

下面给出了如何用空白字符替换所有标点符号,然后用单个空白字符替换多个连续的空白字符:

  1. 首先使用str.replaceAll("\\p{Punct}", " ") 将所有标点字符替换为空白字符,其中\p{Punct} 指定punctuation character,它是!"#$%&'()*+,-./:; ?@[]^_`{|}~.
  2. 链接此替换的输出并将\\s+ 替换为" ",其中\\s+ 指定one or more 空白字符。

演示:

public class Main {
    public static void main(String[] args) {
        String str = "a    b c d; e     f.   g=t";
        str = str.replaceAll("\\p{Punct}", " ").replaceAll("\\s+", " ");
        System.out.println(str);
    }
}

输出:

a b c d e f g t

更新(基于 OP 的评论):

您希望保留',同时删除所有其他标点符号。您可以使用[^\p{L}\d'] 作为要替换的正则表达式模式。正则表达式模式[^\p{L}\d'] 表示不是字母也不是数字,也不是'^ 内的 [] 用作否定模式。

public class Main {
    public static void main(String[] args) {
        String str = "a    won't c d; e     f.   g=t";
        str = str.replaceAll("[^\\p{L}\\d']", " ").replaceAll("\\s+", " ");
        System.out.println(str);
    }
}

输出:

a won't c d e f g t

【讨论】:

  • 这里的“不会”怎么样?我不希望删除 ',否则,它会将单词更改为 won 和 t。
  • @GilCaplan - 我已经发布了一个应该满足这个要求的更新。
  • 好的。谢谢。现在才看到
猜你喜欢
  • 2021-03-12
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2014-10-31
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多