如何按单词的频率对其排序 [英] How to sort the words by their frequency

查看:238
本文介绍了如何按单词的频率对其排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我获取一个输入文本文件,将其转换为数组,对该数组进行排序,然后获取每个单词的频率.我无法弄清楚如何根据频率从高到低的顺序对它们进行排序,而又不导入很多东西(这就是我想要做的事情):

I take an input text file, convert it to an array, sort the array, and then get the frequencies of each word. I can't figure out how to sort them according to their frequencies, from highest to lowest, without importing lots of things (which is what I am trying to do):

//find frequencies
    int count = 0;
    List<String> list = new ArrayList<>();
    for(String s:words){
        if(!list.contains(s)){
            list.add(s);
        }
    }
    for(int i=0;i<list.size();i++){
        for(int j=0;j<words.length;j++){
            if(list.get(i).equals(words[j])){
                count++;
            }
        }

        System.out.println(list.get(i) + "\t" + count);
        count=0;
    }

这将以未排序的顺序返回单词及其频率,例如:

This returns the words with their frequencies in an unsorted order, for example:

the 3
with 7
he 8

我希望将其排序为:

he 8
with 7
the 3

推荐答案

我是这样实现的,

private static class Tuple implements Comparable<Tuple> {
    private int count;
    private String word;

    public Tuple(int count, String word) {
        this.count = count;
        this.word = word;
    }

    @Override
    public int compareTo(Tuple o) {
        return new Integer(this.count).compareTo(o.count);
    }
    public String toString() {
        return word + " " + count;
    }
}

public static void main(String[] args) {
    String[] words = { "the", "he", "he", "he", "he", "he", "he", "he",
            "he", "the", "the", "with", "with", "with", "with", "with",
            "with", "with" };
    // find frequencies
    Arrays.sort(words);
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : words) {
        if (map.containsKey(s)) {
            map.put(s, map.get(s) + 1);
        } else {
            map.put(s, 1);
        }
    }
    List<Tuple> al = new ArrayList<Tuple>();
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        al.add(new Tuple(entry.getValue(), entry.getKey()));
    }
    Collections.sort(al);
    System.out.println(al);
}

输出为

[the 3, with 7, he 8]

这篇关于如何按单词的频率对其排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆