Java文件操作---输出单个文件中常出现的前N个英语单词
如题,读取一个文件,输出单个文件中的前N个英语单词,具体要求是可记录的‘单词’由数字,字母组成,分割符为非字母数字符号。代码如下
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 import java.util.Map; 5 import java.util.Map.Entry; 6 import java.util.Scanner; 7 import java.util.TreeMap; 8 9 public class Traverse3 { 10 public static void main(String[] args) { 11 //读取文件 12 File file=new File("E:\\Harry Potter and the Sorcerer's Stone.txt"); 13 Scanner in=new Scanner(System.in); 14 try { 15 FileReader fr = new FileReader(file); 16 BufferedReader bufr = new BufferedReader(fr); 17 //按行读取返回的字符串 18 String s = null; 19 //将所有s字符串拼接 20 String all = null; 21 while((s=bufr.readLine())!=null){ 22 all = all + s; 23 } 24 //定义TreeMap 25 Map<String,Integer> tm = new TreeMap<>(); 26 //按找非数字字母符号分割字符串,组成字符串数组 27 String[]strs = all.split("[^a-zA-Z0-9]"); 28 //用于存放字符串的数组 29 String[]r1=new String[strs.length]; 30 //用于存放字符串出现次数的数组 31 int[]r2=new int[strs.length]; 32 //读取分割后的字符串数组,使用TreeMap存入字符串(key)及其出现次数(value) 33 for(int i = 0; i < strs.length; i++){ 34 strs[i].toLowerCase(); 35 if(!tm.containsKey(strs[i])){ 36 tm.put(strs[i], 1); 37 }else{ 38 Integer counts = tm.get(strs[i]); 39 tm.put(strs[i], counts+1); 40 } 41 } 42 int j=0; 43 //遍历TreeMap,摘取key和value,分别存入事先构建好的数组 44 for(Entry<String,Integer>entry:tm.entrySet()) { 45 r1[j]=entry.getKey(); 46 r2[j]=entry.getValue(); 47 j++; 48 } 49 //冒泡降序排序 50 for(int p=0;p<strs.length-1;p++) { 51 for(int q=0;q<strs.length-1-p;q++) { 52 if(r2[q]<r2[q+1]) { 53 int temp=r2[q]; 54 r2[q]=r2[q+1]; 55 r2[q+1]=temp; 56 String tems=r1[q]; 57 r1[q]=r1[q+1]; 58 r1[q+1]=tems; 59 } 60 } 61 } 62 int l=in.nextInt(); 63 //存储完成后的数组首元素非字符串(:r2[0]),未能成功消去所以从第二个开始输出。 64 for(int i=1;i<l+1;i++) { 65 System.out.println(r1[i]+":"+r2[i]); 66 } 67 //关闭 68 in.close(); 69 bufr.close(); 70 fr.close(); 71 }catch(Exception e){ 72 e.printStackTrace(); 73 } 74 } 75 76 }
本次任务首次尝试了TreeMap的使用,一开始打算的是直接通过TreeMap完成对字符串的存入,次数统计和排序工作,但是在排序时出现了排序后value值全部为1的问题,同时与完成代码的结果相比,“排序”后的key值也没有对上,后来看到指定的读取文件仅453KB,直接遍历TreeMap把key值和value分存于两个数组,冒泡排序后再输出,也算是取巧了。另外,通过TreeMap抓取字符串的时候出现了一个’空‘字符串,readLine()方法按行读取文档时返回的字符串是不带有回车和换行符的,这个’空‘字符串我并不清楚怎么消去,因此在输出时从第二个元素开始输出。
这次任务暴露出来的主要是对TreeMap的掌握问题,需要多加练习。