- import java.util.*;
- import java.io.*;
- import java.lang.*;
- import java.awt.Frame;
- import java.awt.TextArea;
- class CountPara extends Frame
- {
- CountPara(RandomAccessFile randomR)
- {
- Map<String,Integer> map = new HashMap<String, Integer>();
-
- map = countWords(map,randomR);
-
- countOnce(map);
-
- countFreq(map);
- }
-
- public Map countWords(Map<String,Integer> map, RandomAccessFile raf)
- {
- byte[] b = new byte[1];
- char[] temp = new char[1];
- StringBuffer sb = new StringBuffer();
- String s;
- char c;
-
- try
- {
- while(raf.getFilePointer()<raf.length())
- {
-
-
- raf.readFully(b);
- s = new String(b);
-
- temp = s.toCharArray();
-
- c = temp[0];
-
-
- //从非空格字符开始数算
- while(Character.isLetter(c))
- {
- sb.append(new String(temp));
-
- raf.readFully(b);
- s = new String(b);
- temp = s.toCharArray();
- c = temp[0];
-
- }
-
-
-
- if(map.containsKey(sb.toString()))
- {
- map.put(sb.toString(), 1+map.get(sb.toString()));
- }
-
- else if(sb.length()> 0)
- map.put(sb.toString(), 1);
-
- sb.delete(0,sb.length());
-
-
- }
-
- raf.close();
- }
-
-
- catch (EOFException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
-
- System.out.println("全文共出现"+ map.size() +" 个单词。");
-
- return map;
-
- }
-
- public void countOnce(Map<String, Integer> map)
- {
- Set<String> keySet = map.keySet();
-
- Iterator<String> it = keySet.iterator();
-
- System.out.print("出现一次的单词有: ");
-
- int i = 1;
- while(it.hasNext())
- {
- String s = it.next();
-
-
-
- if(map.get(s)==1)
- {
- System.out.print(i+"."+s+" ");
- i++;
- }
- }
-
- }
-
-
- public void countFreq(Map<String,Integer> map)
- {
- //将map.entry转换成arraylist
- List<Map.Entry<String,Integer>> list = new ArrayList<
- Map.Entry<String,Integer>>(map.entrySet());
-
-
- Collections.sort(list,new Comparator<Map.Entry<String,Integer>>()
- {
- public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2)
- {
- return o1.getValue().compareTo(o2.getValue());
- }
-
- });
-
-
-
- Frame f = new Frame();
-
- TextArea text = new TextArea();
- f.setSize(400,300);
- f.setLocation(300,200);
- text.setRows(50);
- text.setColumns(5);
-
- f.add(text);
- f.setVisible(true);
- for(Map.Entry<String,Integer> mapping:list)
- text.append(mapping.getKey()+":"+mapping.getValue()+" ");
-
- }
-
-
- }
- public class Three
- {
-
- public static void main (String[] args)
- {
- System.out.println("hallelujah!");
- System.out.println();
-
- RandomAccessFile raf = null;
-
-
- try
- {
- raf = new RandomAccessFile("hello.txt","r");
-
- CountPara ctp = new CountPara(raf);
-
- raf.close();
- }
-
-
- catch(EOFException e)
- {
- e.printStackTrace();
- }
-
- catch(IOException e)
- {
- e.printStackTrace();
- }
-
-
- }
- }
复制代码
自己给自己回复吧。 度了好久才一点点度出来。虽然实现了,但是里面的东西还的多消化消化。 望各位大虾予以指教,在个方面要如何改进。:lol |