package programming;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class CountTxtNumber { @SuppressWarnings("unchecked")
public static void main(String[] args) {

String str,word="";
String[] words;
int count,count_once=0;
HashMap<String,Integer> hm=new HashMap<String,Integer>();
try{
RandomAccessFile raf=new RandomAccessFile
("D:\\Java\\javaCompetition\\hello.txt","r"); while((str=raf.readLine())!=null)
{
//以下三行将把str中的所有英文标点符号去掉
           Pattern p=Pattern.compile("[,.?!\\\"\']");
   Matcher m=p.matcher(str);
   str=m.replaceAll("");
   
   //以“ ”为标记将str分割,得到的结果(一个数组)赋值给words
   words=str.split(" ");    /*遍历words数组,以单词为键值、单词出现次数为值。
    * 逐个添加单词(words[i]),若单词已存在,次数(count)加1;
                        若单词不存在,次数赋值为1      */
   for(int i=0;i<words.length;i++)
   if(hm.containsKey(words[i]))
   {
   count=hm.get(words[i]).intValue();
   hm.put(words[i], count+1);
   }
   else
   hm.put(words[i], 1);
   
}
//得到全文中共出现的单词的个数(重复的单词只计算一次)
System.out.println(hm.size());

//由hm.entrySet()得到entryset(此即为HashMap的所有键值对的集合)
        Set<Entry<String, Integer>> entryset=hm.entrySet();
        
         //创建entryset的迭代器it
Iterator<Entry<String, Integer>> it=entryset.iterator();
while(it.hasNext())
{
if(it.next().getValue()==1)//若出现次数为1则count_once自加1
count_once++;          //统计出现次数为1的单词个数
}
System.out.println(count_once);
        
//将由hm.entrySet()得来的entryset按照频率大小由前到后排序
ArrayList<Entry<String, Integer>> al=
new ArrayList<Entry<String, Integer>>(entryset);

//Collections.sort(List<T> arg0, Comparator arg1)方法
Collections.sort(al, new Comparator()
{public int compare(Object o1,Object o2){
Entry<String,Integer> ent1=(Entry<String,Integer>)o1;
Entry<String,Integer> ent2=(Entry<String,Integer>)o2;
return ent2.getValue()-ent1.getValue();
}});
        
//得到排序后的ArrayList的迭代器
    Iterator iter=al.iterator();
    
    while(iter.hasNext())
    {
     Entry<String, Integer> ent=(Entry<String, Integer>)(iter.next());
     System.out.print(ent.getKey()+":");
     System.out.println(ent.getValue());
    }
    raf.close();
}catch(FileNotFoundException e)
{e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}}