看到这个问题为之一愣,这简单多了,在第一部分的基础上把那些存储结构删了,把排序算法删了,设置一个变量,遇到则加一,直到读到文件尾。最后输出单词出现次数。

  程序比较简单也比较,下面就把程序贴出来:

  

 package note1;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.regex.*;
import java.util.Comparator; public class part2 { public static void main(String[] args)
{ //input
Map<String,Integer> numcount=new HashMap<String,Integer>();
Pattern pat=Pattern.compile("\\b[A-Za-z][A-Za-z0-9]*\\b"); String filename="";
String keyWord="";
int count=0; for(int i=0;i<args.length-1;i++)
{
if(args[i].equals("-f"))
{
filename+=args[i+1];
}
else if(args[i].equals("-w"))
{
keyWord+=args[i+1];
}
} try{
BufferedReader in=new BufferedReader(new FileReader(filename)); //process
String temp;
while((temp=in.readLine())!=null)
{
Matcher mth=pat.matcher(temp);
boolean tf=mth.find();
while(tf)
{
String buffer=mth.group().toLowerCase();
if(buffer.equals(keyWord.toLowerCase()))
{
count+=1;
}
tf=mth.find();
}
}
in.close(); //output
System.out.println("keyword "+keyWord+" occurred "+count+" times !"); }catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file");
}
catch(IOException e)
{
System.out.println(e.getMessage());
} }
}

运行结果:

  词频统计-part2-LMLPHP  

  如果想要的是这种方式的话:

  词频统计-part2-LMLPHP

  Over.

05-11 16:16