【问题标题】:Java - Tweet CounterJava - 推文计数器
【发布时间】:2016-07-01 03:55:45
【问题描述】:

我制作了一个应用程序,当给定关键字时,它会打印 500 条最新推文,例如“猫”。

我想使用带有正则表达式的String.split() 拆分推文中的所有单词,然后使用HashMap 来存储每个单词并使用循环来增加每个单词的整数值,每次在推文。

【问题讨论】:

    标签: java regex twitter


    【解决方案1】:

    您可以使用 Java 8 流:

    String[] words = tweetText.split(" ");
    Map<String, Integer> wordCount = Arrays.stream(words)
        .collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
    

    如果你想不区分大小写:

    Map<String, Integer> wordCount = Arrays.stream(words)
        .map(String::toLowerCase)
        .collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
    

    仅查找特定单词:

    Map<String, Integer> wordCount = Arrays.stream(words)
        .map(String::toLowerCase)
        .filter(word -> wordsToMatch.contains(word))
        .collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
    

    其中 wordsToMatch 可以是您要查找的单词的集合或列表。

    【讨论】:

      【解决方案2】:

      应该是这样的:

          for (String word : tweetText.split("\\s+")) {
             wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);
          }
      

      wordMap.getOrDefault(word, 0) 可能仅适用于 java 8。由于您的地图,该代码会将您的推文分成单独的单词并计算每条推文的单词。

      【讨论】:

        【解决方案3】:

        我将扩展 HashMap&lt;String, Integer&gt; 以提供一个使用该值作为计数器的 put(key)

        class WordCounter extends HashMap<String, Integer> {
        
            public void put(String key) { 
                Integer number = this.get(key);
                this.put(key, number == null ? 1 : number + 1);
            }
        
            public static void main (String[] args) throws java.lang.Exception
            {
                WordCounter wc = new WordCounter();
                for(String word : "this is a test and this is too".split(" ")) {
                    wc.put(word);
                }
                System.out.println(wc);
            }
        }
        

        输出:

        {a=1, test=1, too=1, and=1, this=2, is=2}
        

        【讨论】:

          猜你喜欢
          • 2011-04-19
          • 1970-01-01
          • 2017-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-18
          • 1970-01-01
          相关资源
          最近更新 更多