首页 > 代码库 > 取前k个出现频率最大的单词
取前k个出现频率最大的单词
package aprioriproduct; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.print.DocFlavor.BYTE_ARRAY; public class AprioriProduct { private static TreeMap<String,Integer>tm=new TreeMap(); private static int k=4; public static void main(String []args) { FileReader fr; try{ fr=new FileReader("C:\\Examples6.txt"); BufferedReader br=new BufferedReader(fr); String aline; while((aline=br.readLine())!=null) { String str =new String(aline); //System.out.println(str); String arrayList[]=str.split(",|\\.|:|;| "); for(String temp:arrayList) { //System.out.println(temp); if(!tm.containsKey(temp)) { tm.put(temp,1); } else { tm.put(temp,tm.get(temp)+1); } } } tm.remove(tm.firstKey()); List arrayList = new ArrayList(tm.entrySet()); Collections.sort(arrayList, new Comparator() { public int compare(Object o1, Object o2) { Map.Entry obj1 = (Map.Entry) o1; Map.Entry obj2 = (Map.Entry) o2; return -((Integer) obj1.getValue()).compareTo((Integer) obj2 .getValue()); } }); for (int i = 0; i < k; i++) { System.out.println(((Map.Entry) arrayList.get(i)).getKey() + " " + ((Map.Entry) arrayList.get(i)).getValue()); } for(Iterator it =tm.keySet().iterator();it.hasNext();) { String key =it.next().toString(); System.out.print(key+" "); System.out.println(tm.get(key)); } fr.close(); br.close(); } catch(Exception e) { e.printStackTrace(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。