【问题标题】:How to print just the top 10 words and their frequency from a HashMap?如何仅打印 HashMap 中的前 10 个单词及其频率?
【发布时间】:2017-12-09 20:57:51
【问题描述】:

我的代码有问题。 我正在阅读带有一些文本的文件,然后计算单词及其频率。然后我试图打印出文本中最常用的 10 个单词。

但是,通过我尝试过的方法(例如,将 for 循环设置为在 10 次迭代后停止),我以相同的方式仅打印了 10 次单词。否则,我可以按频率打印文件中的所有单词。我只需要前 10 个最常用的单词。

ArrayList<Integer> values = new ArrayList<>();
    values.addAll(wordcount.values());
    Collections.sort(values, Collections.reverseOrder());
    int last_i = -1;
    for(Integer i: values) {
        if (last_i == i)
            continue;
        last_i = i;
        System.out.println("The top 10 words are: ");
       // for (int count = 0; count < 10; count++) {
            for (String s : wordcount.keySet())
                if (wordcount.get(s) == i)
                    System.out.println(s + " : " + i);
           }
       }
}

请在上面找到“有问题的”代码。我正在使用

BufferedReader

读取文本文件,然后删除所有标点符号和可能导致同一单词在我的 HashMap 中显示为两个不同条目的内容。

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 好吧,只需制作 HashMap 并按值对其进行排序,然后打印出 Key:Value 对。
  • Thisleetcode 上的讨论解决了类似的问题。

标签: java hashmap word-count


【解决方案1】:

这是一个带有 lambda 的 Java 8 示例:

        Map<String, Integer> wordcount = new HashMap<>();
        wordcount.put("two", 20);
        wordcount.put("five", 50);
        wordcount.put("three", 30);
        wordcount.put("four", 40);
        wordcount.put("one", 10);
        wordcount.put("six", 60);
        wordcount.put("eight", 80);
        wordcount.put("twelve", 1);
        wordcount.put("nine", 90);
        wordcount.put("ten", 100);
        wordcount.put("seven", 70);
        wordcount.put("eleven", 1);
        wordcount.put("15", 1);
        wordcount.put("13", 2);
        wordcount.put("16", 4);
        wordcount.put("14", 3);
        wordcount.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
                .limit(10)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                )).forEach((s, integer) -> System.out.println(String.format("%s : %s", s, integer)));

应该打印如下内容:

ten : 100
nine : 90
eight : 80
seven : 70
six : 60
five : 50
four : 40
three : 30
two : 20
one : 10

【讨论】:

    【解决方案2】:

    首先,您需要在 Map 的帮助下计算每个单词在文本中重复的次数,然后以相反的顺序对 map 条目进行排序,结果最常见的单词将位于集合的开头并打印前十个元素来自这个集合。

    public void printTopTenWordsByFrequencyFrom(List<String> text) {
        Map<String, Integer> map = new HashMap<>();
        for(String word : text) {
            Integer times = map.get(word);
            if(times == null) {
                map.put(word, 1);
            } else {
                map.put(word, times + 1);
            }
        }
        map.entrySet().stream()
                      .sorted((one, another) -> - one.getValue().compareTo(another.getValue())) //sort entries to reverse order  
                      .limit(10) 
                      .forEach(entry -> entry.getKey() + " : " + entry.getValue());
    }
    

    没有流和 lambda 的版本:

      public void printTopTenWordsByFrequencyFrom(List<String> text) {
            Map<String, Integer> map = new HashMap<>();
            for(String word : text) {
                Integer times = map.get(word);
                if(times == null) {
                    map.put(word, 1);
                } else {
                    map.put(word, times + 1);
                }
            }
            List<Map.Entry<String, Integer>> statistics = new ArrayList<>(map.entrySet());
            Collections.sort(statistics, new Comparator<Map.Entry<String, Integer> {
    
                int compare(Map.Entry<String, Integer> one, Map.Entry<String, Integer> another) {
                    return - one.getValue().compareTo(another.getValue()); 
                }
            });
            List<Map.Entry<String, Integer>> topTen = statistics.sublist(0, 9);
            for(Map.Entry<String, Integer> word : topTen) {
                System.out.println(word.getKey() + " : " + word.getValue());
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      相关资源
      最近更新 更多