运行截图:

实现代码:
1 package Ape;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7 import java.io.IOException;
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
10
11 public class CountPlus1 {
12
13 public CountPlus1() {
14 // TODO Auto-generated constructor stub
15 }
16
17 public static void main(String[] args) {
18 // TODO Auto-generated method stub
19 String temp=null;
20 Pattern pattern=Pattern.compile("[^a-zA-Z]"); //匹配非字母
21 Pattern pattern1=Pattern.compile("^[a-zA-Z]{3,}"); //剔除无意义单词如:is,a,at等
22 String []ape=new String[10000]; //存储单词
23 int []num=new int[10000];//存储数量
24 int count=0; //记录多少个不同的单词,即ape数组的长度
25 File filepath=new File("Harry Potter and the Sorcerer's Stone.txt");//导入文件
26 try {
27 FileReader reader=new FileReader(filepath);
28 BufferedReader br=new BufferedReader(reader);
29 try {
30 while((temp=br.readLine())!=null) //读取到结尾时停止
31 {
32 Matcher matcher=pattern.matcher(temp); //匹配字符串
33 if(matcher.find())
34 temp=matcher.replaceAll(" "); //替换字符串
35 String str[]=temp.toLowerCase().trim().split(" "); //分割字符串
36 if(str.length>0) { //如果字符串中有单词
37 for(int j=0;j<str.length;j++) {
38 Matcher matcher1=pattern1.matcher(str[j]); //剔除无意义单词
39 if(count==0) {
40 ape[count]=str[j];
41 num[count]++;
42 count++;
43 }
44 else if(matcher1.find()){ //进行计数
45 int tempnum=count;
46 for(int k=0;k<tempnum;k++) {
47 if(ape[k].equals(str[j]))
48 {
49 num[k]++;
50 break;
51 }
52 else if(k==tempnum-1){
53 ape[count]=str[j];
54 num[count]++;
55 count++;
56 }
57 }
58 }
59 }
60 }
61 }
62 } catch (IOException e) {
63 // TODO Auto-generated catch block
64 e.printStackTrace();
65 }
66 } catch (FileNotFoundException e) {
67 // TODO Auto-generated catch block
68 e.printStackTrace();
69 }
70 for(int i=0;i<count;i++) //冒泡排序法实现倒序排序
71 for(int j=0;j<count-1-i;j++)
72 {
73 int numtemp;
74 String tempch;
75 if(num[j]<num[j+1])
76 {
77 numtemp=num[j];num[j]=num[j+1];num[j+1]=numtemp;
78 tempch=ape[j];ape[j]=ape[j+1];ape[j+1]=tempch;
79 }
80 }
81 for(int i=0;i<count;i++) { //输出单词以及对应数量
82 System.out.println(ape[i]+" "+num[i]);
83 }
84 }
85
86 }