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

このクラスのインスタンスの配列を単語ごとに 1 つ作成し、 を使用して配列を並べ替えます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値とその頻度を保持する型のオブジェクトを作成する必要があります。

次に、タイプのリストでa を実装compareToまたは使用しComparatorて呼び出すことができますCollections.sort()Word

于 2014-03-19T19:14:43.387 に答える
0

代わりにaを使用して、キーとしてのキーと値としての頻度のMap<String, Integer>両方を保存しますString。初期値は 1 です。単語が既に存在する場合は、値を 1 増やして更新します。次に、このマップを a Map<Integer, List<String>>(またはGuavaMultimap )に変換し、Integer値をキーとして使用し、キーを値として保存Stringします。

于 2014-03-19T19:16:49.640 に答える