词频统计-part2
看到这个问题为之一愣,这简单多了,在第一部分的基础上把那些存储结构删了,把排序算法删了,设置一个变量,遇到则加一,直到读到文件尾。最后输出单词出现次数。
程序比较简单也比较,下面就把程序贴出来:
1 package note1; 2 import java.io.BufferedReader; 3 import java.io.FileReader; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.util.*; 7 import java.util.regex.*; 8 import java.util.Comparator; 9 10 public class part2 { 11 12 public static void main(String[] args) 13 { 14 15 //input 16 Map<String,Integer> numcount=new HashMap<String,Integer>(); 17 Pattern pat=Pattern.compile("\\b[A-Za-z][A-Za-z0-9]*\\b"); 18 19 String filename=""; 20 String keyWord=""; 21 int count=0; 22 23 for(int i=0;i<args.length-1;i++) 24 { 25 if(args[i].equals("-f")) 26 { 27 filename+=args[i+1]; 28 } 29 else if(args[i].equals("-w")) 30 { 31 keyWord+=args[i+1]; 32 } 33 } 34 35 try{ 36 BufferedReader in=new BufferedReader(new FileReader(filename)); 37 38 //process 39 String temp; 40 while((temp=in.readLine())!=null) 41 { 42 Matcher mth=pat.matcher(temp); 43 boolean tf=mth.find(); 44 while(tf) 45 { 46 String buffer=mth.group().toLowerCase(); 47 if(buffer.equals(keyWord.toLowerCase())) 48 { 49 count+=1; 50 } 51 tf=mth.find(); 52 } 53 } 54 in.close(); 55 56 //output 57 System.out.println("keyword "+keyWord+" occurred "+count+" times !"); 58 59 }catch(FileNotFoundException e) 60 { 61 System.out.println("Cannot find the specified file"); 62 } 63 catch(IOException e) 64 { 65 System.out.println(e.getMessage()); 66 } 67 68 } 69 } 70 71 72
运行结果:
如果想要的是这种方式的话:
Over.