我有一个英文的文本,已经存为了String[],现在想统计这个文本的词频,并且从高到底排序,应该如何写?

解决方案 »

  1.   


        public static void sort(String[] str){
    for(int i=0;i<str.length-1;i++){
    String maxStr = str[i];
    int index = i;
    for(int j=i+1;j<str.length;j++){
    if(maxStr.compareTo(str[j]) < 0){
    maxStr = str[j];
    index = j;
    }
    }
    str[index] = str[i];
    str[i] = maxStr;
    }
    }写个main方法调用一下就可以!
      

  2.   

    存于TreeMap中,value存单词,key存词频。
      

  3.   


    public class Test { public static void main(String[] args) {
    String[] strs = new String[]{"a","b","a"};
    Map<String, Integer> map = new HashMap<String, Integer>();
    for(String s : strs){
    Integer key = map.get(s);
    if(key == null){
    map.put(s, 1);
    }else{
    map.put(s, key.intValue() + 1);
    }
    }
    Set<Entry<String, Integer>> set = map.entrySet();
    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
    Iterator<Entry<String, Integer>> iter = set.iterator();
    while(iter.hasNext()){
    list.add(iter.next());
    }
    Collections.sort(list, new ComparatorEntry());
    for(Entry<String, Integer> entry : list){
    System.out.println(entry.getKey() + " : " + entry.getValue());
    }
    }
    }class ComparatorEntry implements Comparator<Entry<String, Integer>>{
    @Override
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
    return o2.getValue().intValue() - o1.getValue().intValue();
    }
    }
      

  4.   

    3楼的回复非常有用!!多谢!!
    我还有个问题,最后的结果是存在了list中,对吧?那如果我想去list中词频最高的20个再对其词频进行计算,我要怎么写呢?