1

我获取一个输入文本文件,将其转换为数组,对数组进行排序,然后获取每个单词的频率。我不知道如何根据它们的频率从最高到最低对它们进行排序,而不导入很多东西(这是我想要做的):

//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;
    }

这会以未排序的顺序返回具有频率的单词,例如:

the 3
with 7
he 8

等等

我希望将其排序为:

he 8
with 7
the 3
4

4 回答 4

2

我建议使用一个小的帮助类:

class WordFreq implements Comparable<WordFreq> {
   final String word;
   int freq;
   @Override public int compareTo(WordFreq that) {
     return Integer.compare(this.freq, that.freq);
   }
}

构建一个此类实例的数组,每个单词一个,然后使用 对数组进行排序Arrays.sort

于 2014-03-19T19:13:55.167 回答
1

我是这样实现的,

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]
于 2014-03-19T19:26:08.727 回答
0

您应该创建一个类型的对象Word来保存单词的String值及其频率。

然后你可以在你的类型列表上实现compareTo或使用Comparator和调用Collections.sort()Word

于 2014-03-19T19:14:43.387 回答
0

使用 aMap<String, Integer>代替将您的Stringas 键和频率存储为值,初始值为 1。如果单词已经存在,只需将值增加 1 来更新值。然后,将此映射转换为 a Map<Integer, List<String>>(或GuavaMultimap)和使用Integer值作为键和String键将它们存储为值。

于 2014-03-19T19:16:49.640 回答