首页 > 编程 > Java > 正文

java读取英语文本,找出频率最高的20个单词

2019-11-06 07:17:23
字体:
来源:转载
供稿:网友

利用集合类,其中按照map中value排列需要考虑一下具体思路,最后结合list完成排列

/** * Created by changqing on 2017/3/4. */import java.io.*;import java.util.*;public class test {    public static void main(String [] args) throws Exception {        System.out.PRintln("starting to read file");        File file=new File("test.txt");        BufferedReader bf=new BufferedReader(new FileReader(file));        String line;        String reg="//s+";//正则表达式,把句子划分为一个个单词        TreeMap<String,Integer> tm= new TreeMap<String, Integer>();        while((line=bf.readLine())!=null) {           String []strs=line.split(reg);            for(String str:strs)            {                str=str.replaceAll("[//p{Punct}//pP]", ""); //去掉单词中含有的标点符号                if(!tm.containsKey(str))                {                    tm.put(str,1);                }                else                    tm.put(str,tm.get(str)+1);            }        }        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(tm.entrySet());        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {            public int compare(Map.Entry<String, Integer> o1,                               Map.Entry<String, Integer> o2) {                return (o2.getValue() - o1.getValue());            }        });        for (int i = 0; i <20 ; i++) {            System.out.println(list.get(i).getKey());        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表