单词统计作业

 1 package j;
 2 
 3     import java.io.BufferedReader;
 4     import java.io.BufferedWriter;
 5     import java.io.FileReader;
 6     import java.io.FileWriter;
 7     import java.io.IOException;
 8     import java.util.Iterator;
 9     import java.util.TreeMap;
10     import java.util.regex.Matcher;
11     import java.util.regex.Pattern;
12     public class lolo{
13 
14         public static void main(String[] args) throws IOException {
15             String addr="C:/cjf/123.txt"; 
16             BufferedReader bufr = new BufferedReader(new FileReader(addr));
17             StringBuffer sbuf = new StringBuffer();
18             String line = null;
19             while ((line = bufr.readLine()) != null) {
20                 sbuf.append(line);
21             }
22             bufr.close();
23             Pattern expression = Pattern.compile("[a-zA-Z]+");
24             String str1 = sbuf.toString().toLowerCase();
25             Matcher matcher = expression.matcher(str1);
26             TreeMap myTreeMap = new TreeMap();
27             int n = 0;
28             Object word = null;
29             Object num = null;
30             while (matcher.find()) {
31                 word = matcher.group();
32                 n++;
33                 if (myTreeMap.containsKey(word)) {
34                     num = myTreeMap.get(word);
35                     Integer count = (Integer) num;
36                     myTreeMap.put(word, count.intValue() + 1);
37                 } else {
38                     myTreeMap.put(word, new Integer(1));
39                 }
40             }
41             System.out.println("文章内容如下:");
42             System.out.println(str1);
43             System.out.println("统计分析如下:");
44             System.out.println("文章中单词总数:" + n+"个");
45             System.out.println("具体的信息在当前目录的lwl.txt文件中");
46             BufferedWriter bufw=new BufferedWriter(new FileWriter("C:/cjf/456.txt"));
47             Iterator iter=myTreeMap.keySet().iterator();
48             Object key=null;
49             bufw.write("文件来自:"+addr+"内容如下:");
50             bufw.write(sbuf.toString());
51             bufw.newLine();
52             while(iter.hasNext()){
53                  key=iter.next();
54                  System.out.println(key+":"+myTreeMap.get(key));
55                  
56                  bufw.write((String)key+":"+myTreeMap.get(key));
57                  bufw.newLine();
58             }
59             bufw.write("统计分析如下:");
60             bufw.write("文章中单词总数:" + n+"个");
61             bufw.newLine();
62             bufw.write("文章中不同单词总数:" + myTreeMap.size()+"个");
63             bufw.close();
64         
65 }}

 思路:在程序外建两个写英文段落的txt文档,用于程序内访问使用,中间的核心代码参考了网上的方法;

感想:建立文档很容易,在程序中使用也参考资料就很容易掌握,关键是中间的核心操作代码参考了网上的代码,虽然是看懂了,但还是缺乏自己思考的能力,以后还是要练习。

posted @ 2018-10-11 22:22  Tsui98'  阅读(176)  评论(0编辑  收藏  举报