• 第一周 词频统计


        这是我的第一篇博客,说起来有些惭愧,作为一个程序猿竟然至今没写过一篇技术博客。在这里,先向读到这篇博客的读者致歉,原谅我粗糙的表达能力。

      在读研究生之前,“程序员”对我来说,只是三个字的组合,我并不了解程序员的世界,也不知道一个程序员的基本素养(这个词是从亮哥那听来的,但是是从杨老师那了解的)。在这里,我要向我的导师--杨贵福老师表示深深的感谢,他教会了我许多作为一个程序员应有的工作的态度以及责任。

       接下来谈谈我第一次上我导师的课的感受。我现在是研二,两年来我从没听过我的导师上的课。上周五是我第一次听他上课,第一感觉就是风格迥异。他上课的风格和我以前的老师的style完全不一样。不按照书本上的来(当然研究生也没有特定的课本),完全根据自己从事工程师多年的经验来给我们讲解软件工程。第二感觉就是内容充实、丰富。但是,可能对于初学者来说有点压力过大。在这次课上,我听到一个非常引起我注意的问题:“教师是服务行业吗?”。杨老师给出的答案是:“教师不是服务行业”。的确,现在大多数学生都认为教师是服务行业。“我”交了学费,学校提供这一服务。“我”是顾客,“我”就是上帝。“我”可以对你提供的服务进行评论,“我”也可以选择是否接受你的服务。我觉得正是由于这种想法,才组织了我们的求知欲。这里就不再赘述这一话题。

        进入主题。下面谈谈我对词频统计系统的看法。我的方案是:源文件经过一个引擎解析出这个文件有多少个不同的单词以及每个单词出现的次数,最后显示在频幕上。

    主要技术包括:1.文件的上传。文件上传有很多方式,这里我选择的是SmartUpload.jar。个人觉得简单好用。

                       2.单词的分割。涉及到标点符号的处理。我在网上看到一个很好的处理方案。采用java正则替换标点。参考地址:http://blog.csdn.net/wangran51/article/details/7764256

           3.数据的显示。数据的显示有很多种方案。比如文字,图表,表格等。这里我用的是百度的产品EChart.是免费的,而且官网有纤细的教程。参考地址:http://echarts.baidu.com/index.html

    index.jsp代码如下:

    1 <div align="center" style="margin-top:50px;">
    2   <form action="servlet/fileupload_servlet" method="post" enctype="multipart/form-data">
    3     <input type="file" name="file_name" id="file_name" accept=".txt" style="height: 40px;  500px; border: 1px solid;">
    4     <input type="submit" value="检索" style="height: 40px;">
    5   </form>
    6   </div>

    fileupload_servlet代码如下:

     1 public void doPost(HttpServletRequest request, HttpServletResponse response)
     2             throws ServletException, IOException {
     3 
     4         request.setCharacterEncoding("GBK");
     5         //设置文件保存的路径
     6         Date currentData = new Date();
     7         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
     8         String cal = sdf.format(currentData);
     9         String filePath = getServletContext().getRealPath("/") + "upload/"+cal;
    10         
    11         //初始化SmartUpload
    12         SmartUpload upload = new SmartUpload();
    13         upload.initialize(this.getServletConfig(), request, response);
    14         @SuppressWarnings("unused")
    15         int count = 0;
    16         com.jspsmart.upload.File tempFile = null;
    17         //开始上传
    18         try {
    19             upload.setMaxFileSize(10*1024*1024);//设置文件大小的上限10M
    20             upload.setAllowedFilesList("txt");//设置允许上传的文件格式,多个用,分开
    21             upload.upload();//上传文件
    22             
    23             // 如果文件夹不存在 则创建这个文件夹
    24             File file = new File(filePath);
    25             if (!file.exists()) {
    26                 file.mkdir();
    27             }
    28             count = upload.save(filePath);//保存文件到指定路径
    29             
    30             for (int i = 0; i < upload.getFiles().getCount(); i++) {
    31                 tempFile = upload.getFiles().getFile(i);//读取刚上传的文件
    32 //                File file1=new File(filePath+tempFile.getFileName());
    33 //                System.out.println("-------------------------------------------------");
    34 //                System.out.println("表单项名称:" + tempFile.getFieldName());
    35 //                System.out.println("文件名:" + tempFile.getFileName());
    36 //                System.out.println("文件长度:" + tempFile.getSize());
    37 //                System.out.println("文件扩展名:" + tempFile.getFileExt());
    38 //                System.out.println("文件全名:" + tempFile.getFilePathName());
    39             }
    40         } catch (SmartUploadException e) {
    41             e.printStackTrace();
    42         } catch (SecurityException e) {
    43             System.out.println("格式不符合");
    44         }
    45 //        System.out.println(count);
    46         
    47         //////////////////////////////读取文件///////////////////////////////
    48         
    49         Map<String,Integer> map = FileUtil.readtxtFile(filePath+"/"+tempFile.getFileName());
    50         System.out.println(map.toString());
    51         
    52         request.getSession().setAttribute("data", map);
    53         String path = request.getContextPath();
    54         response.sendRedirect(path+"/Chart.jsp");
    55     }

    FileUtil.java代码如下:

    package util;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class FileUtil {
    
        /***
         * 读取文件,解析出单词,并统计单词数量
         * @param filePath
         * 文件路径
         * @return
         * 返回Map对象,key是单词,value对应单词出现的次数
         */
        public static Map<String,Integer> readtxtFile(String filePath) {
            Map<String, Integer> index_map = new HashMap<String, Integer>();
            BufferedReader reader = null;
            File file = new File(filePath);
            try {
                FileInputStream in = new FileInputStream(file);
                reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                String lineText = "";
                while((lineText=reader.readLine())!= null) {
                    lineText = lineText.replaceAll("\p{Punct}", " ").trim();//去除标点符号
    //                lineText = lineText.replaceAll("\pP", " ").trim();
                    System.out.println(lineText);
                    
                    String[] lineArray = lineText.split(" ");
                    
                    for(String word:lineArray) {
                        word = word.toLowerCase().trim();
                        if(word.length()>0)
                            if(index_map.containsKey(word)) {
                                int value = index_map.get(word)+1;
                                index_map.remove(word);
                                index_map.put(word, value);
                            }
                            else {
                                index_map.put(word, 1);
                            }
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return index_map;
        }
    }

    Chart.jsp代码如下:

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>统计图</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18 
    19     <!-- Step1 引入EChart.js -->
    20     <script type="text/javascript" src="js/echarts.min.js"></script>
    21   </head>
    22   
    23   <body>
    24   <!-- step2 建立一个图表容器 -->
    25     <div id="main" style=" auto;height:500px;"></div>
    26     <!-- step3 编写js代码 -->
    27     <script type="text/javascript">
    28         // 基于准备好的dom,初始化echarts实例
    29         var myChart = echarts.init(document.getElementById('main'));
    30 
    31         var x_data = new Array();//x轴数据
    32         var y_data = new Array();//y轴数据
    33         <%
    34         //从后台读取数据,复制给x_data和有y_data
    35         Map<String,Integer> data_map = (Map<String,Integer>)request.getSession().getAttribute("data");
    36         Set set = data_map.entrySet();        
    37         Iterator i = set.iterator(); 
    38         int index = 0;       
    39         while(i.hasNext()){     
    40              Map.Entry<String, Integer> entry1=(Map.Entry<String, Integer>)i.next();       
    41         %>
    42             x_data[<%=index%>] = '<%=entry1.getKey()%>';
    43             y_data[<%=index%>] = <%=entry1.getValue().intValue()%>;
    44         <%
    45             index++;
    46         }
    47         %>
    48         
    49         // 指定图表的配置项和数据
    50         var option = {
    51             title: {
    52                 text: '词频统计图'
    53             },
    54             tooltip: {},
    55             legend: {
    56                 data:['词频']
    57             },
    58             xAxis: {
    59                 data: x_data
    60             },
    61             yAxis: {},
    62             series: [{
    63                 name: '词频',
    64                 type: 'bar',
    65                 data: y_data
    66             }]
    67         };
    68         myChart.setOption(option);
    69     </script>
    70   </body>
    71 </html>

    效果如下图所示:

  • 相关阅读:
    Oracle-数据库的隔离级别测试
    Oracle Filter执行计划
    webug4.0靶场之文件包含
    webug4.0靶场之文件上传
    webug4.0靶场之越权查看admin
    webug4.0靶场之支付漏洞
    webug4.0靶场之越权修改密码
    webug4.0靶场通关之XSS
    webug4.0靶场通关之任意文件下载
    MSF学习之旅之信息收集工具使用
  • 原文地址:https://www.cnblogs.com/charliePU/p/5252425.html
Copyright © 2020-2023  润新知