软件体系结构课程设计:词频统计程序(包含英文单词和数字double,int)

我用了三个类:一个菜单Menu类,一个中间算法处理WordFrequency,一个结果显示DisplayFace类.

DisplayFace中我用了一个jfreechart来做界面显示

map作为三个类的中间传递的参数

实现了map<key,value>的按照key和value排序

做完这个程序我感觉自己的程序一步步在简化,这个过程我感觉自己挺笨拙的,一开始想到的都是最笨的办法进行文件学些、排序,没想过map,以前也从没用过map,后来在写程序的过程中,自己总是在想办法,然后百度搜怎么解决这个问题,然后自己看别人怎么实现的,看懂了,然后拿来用在自己的程序当中,一开始界面我不知道做成什么样的,厚爱搜到草莓在努力的博客园里面的界面,然后我的菜单界面也实现成和他一样。我很享受写程序这个过程,不仅仅是写程序,关键是在想办法,然后解决问题,这个过程中成就感油然而生,导致每天走在路上,吃饭都会想这个问题怎么解决,上课被老师拿粉笔打,甚至逃课。。。。。。。。。。。。。。

希望大家看了我的程序都说说我程序的不足吧,或者哪些地方你们有更好的解决办法,都可以评论,我希望我们都能互相学习,共同进步。。。。。。。。。。

1:Menu类

  1 package com.cn.ldk.worldFrequency;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import javax.swing.*;
  6 
  7 public class Menu {    
  8     public static void main(String[] args){
  9         MenuFrame frame=new MenuFrame();
 10         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 11         frame.setVisible(true);
 12     }
 13 }
 14 
 15 @SuppressWarnings("serial")
 16 class MenuFrame extends JFrame{
 17     public static final int DEFAULT_WIDTH=500;
 18     public static final int DEFAULT_HEIGHT=400;
 19     public MenuFrame(){
 20         setTitle("词频统计程序");
 21         setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
 22         MenuPanel panel=new MenuPanel();
 23         panel.setLayout(new GridLayout(4,2));
 24         add(panel);
 25         panel.setBounds(0,0,500,400);
 26         setLayout(new BorderLayout());
 27         panel.setVisible(true);
 28     }    
 29 }
 30 
 31 @SuppressWarnings("serial")
 32 class MenuPanel extends JPanel{
 33     public static String filepath1 = "F:/test/source.txt";
 34     public static String filepath2 = "F:/test/output.txt";
 35     public static String str1=filepath1;;
 36     public static String str2=filepath2;
 37     
 38     public static JTextField source = new JTextField(filepath1,20);
 39     public static JTextField output = new JTextField(filepath2,20);
 40     @SuppressWarnings("unchecked")
 41     public MenuPanel(){
 42         JPanel panel1 = new JPanel();
 43         JPanel panel2 = new JPanel();
 44         JPanel panel3 = new JPanel();
 45         JPanel panel4 = new JPanel();
 46         
 47         JLabel label1 = new JLabel("源文件位置:");
 48         JLabel label2 = new JLabel("保存文件位置:");
 49         JLabel label3 = new JLabel("语言种类:"); 
 50         
 51         label1.setFont(new Font("黑体",Font.LAYOUT_LEFT_TO_RIGHT,18)); 
 52         label2.setFont(new Font("黑体",Font.LAYOUT_LEFT_TO_RIGHT,18)); 
 53         label3.setFont(new Font("黑体",Font.LAYOUT_LEFT_TO_RIGHT,18)); 
 54         
 55         JButton button3 = new JButton("...");
 56         JButton button4 = new JButton("...");
 57         
 58         JComboBox language = new JComboBox();
 59         language.addItem("English");
 60         
 61         JButton button1 = new JButton("开始分析");
 62         JButton button2 = new JButton("退出");
 63         
 64         panel1.add(label1);
 65         panel1.add(source);
 66         panel1.add(button3);
 67         
 68         panel2.add(label2);
 69         panel2.add(output);
 70         panel2.add(button4);
 71         
 72         panel3.add(label3);
 73         panel3.add(language);
 74         
 75         panel4.add(button1);
 76         panel4.add(button2);
 77         
 78         add(panel1);
 79         add(panel2);
 80         add(panel3);
 81         add(panel4);
 82         
 83     button1.addActionListener(new ActionListener(){
 84         public void actionPerformed(ActionEvent e){
 85             try {
 86                 WordFrequency.readFile(str1);
 87             } catch (Exception e1) {
 88                 e1.printStackTrace();
 89             }
 90             
 91             WordFrequency wf = new WordFrequency();
 92             try {
 93                 wf.writeFile(str2);
 94             } catch (Exception e1) {
 95                 e1.printStackTrace();
 96             }
 97             
 98             DisplayFace frame = new DisplayFace();
 99               frame.setSize(600, 600);
100               frame.setVisible(true);    
101         }
102     });
103         
104         
105         
106     button2.addActionListener(new ActionListener(){
107         public void actionPerformed(ActionEvent e){
108                 System.exit(0);
109         }
110     });
111     
112 
113     button3.addActionListener(new ActionListener(){        
114         public void actionPerformed(ActionEvent e){
115             JFileChooser fileChooser = new JFileChooser();  
116             fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);  
117             fileChooser.setDialogTitle("选择文件");  
118             int ret = fileChooser.showOpenDialog(null);  
119             if (ret == JFileChooser.APPROVE_OPTION) {   
120                 String str= fileChooser.getSelectedFile().getAbsolutePath();
121                  str1 = str.replace("\\", "/");
122                  source.setText(str1);
123             }
124             
125         }
126         
127     });
128     
129 
130     button4.addActionListener(new ActionListener(){        
131         public void actionPerformed(ActionEvent e){
132             JFileChooser fileChooser = new JFileChooser();  
133             fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);  
134             fileChooser.setDialogTitle("选择文件");  
135             int ret = fileChooser.showOpenDialog(null);  
136             if (ret == JFileChooser.APPROVE_OPTION) {   
137                 String str= fileChooser.getSelectedFile().getAbsolutePath();
138                  str2 = str.replace("\\", "/");
139                  output.setText(str2);
140             }
141         }
142     });
143     
144     
145     }
146     
147 }

2:WordFrequency类

 1 package com.cn.ldk.worldFrequency;
 2 
 3 import java.io.*;
 4 import java.util.*;
 5  
 6 public class WordFrequency{
 7     public static TreeMap<String,Integer> map = new TreeMap<String,Integer>();
 8     public static Set<String> key = map.keySet();
 9     public static String file1 = "F:/test/source.txt";
10     public static List<String> listKey=new ArrayList<String>();
11     @SuppressWarnings("unchecked")
12     public static List listValue = new ArrayList();
13     
14     public static void readFile(String file)throws Exception{
15         BufferedReader br = new BufferedReader(new FileReader(file));
16         String line = null;
17         
18         while((line=br.readLine())!=null){
19             line.toLowerCase();      
20             String reg1 = " ";
21             String reg2 = "\\w+";
22             String reg3 = "^[0-9]+(\\.[0-9]+)?$";
23             String str[] = line.split(reg1);
24             for(String s: str){     
25                 if(s.matches(reg2)||s.matches(reg3)){
26                     if(!map.containsKey(s)){
27                         map.put(s,1);
28                     }
29                     else{
30                         map.put(s,map.get(s)+1);
31                     }
32                 }
33             }
34         }
35         
36         for (Iterator<String> it = key.iterator(); it.hasNext();){
37             String s = it.next();
38             System.out.println(s+" : "+map.get(s));
39         }
40         br.close();
41     }
42     @SuppressWarnings({ "unchecked", "static-access" })
43     public void writeFile(String file)throws Exception{
44           BufferedWriter bw = new BufferedWriter(new FileWriter(file));
45           bw.write("词频统计:"+"\r\n");
46           bw.write("单词   :   词频"+"\r\n");
47           DisplayFace df = new DisplayFace();
48           Map<String,Integer> map1 = new LinkedHashMap<String,Integer>();
49             map1 = df.sortByValue1(map);
50             Set<String> key1 = map1.keySet();
51             for (Iterator<String> it = key1.iterator(); it.hasNext();){
52                 String s = it.next();    
53                 bw.write(s+"   :   "+map1.get(s)+"\r\n");
54             }
55           bw.close();
56     
57     }
58 }

3:DisplayFace类

  1 package com.cn.ldk.worldFrequency;
  2 
  3 import java.awt.BorderLayout;
  4 import java.awt.Dimension;
  5 import java.awt.Font;
  6 
  7 import java.awt.event.ActionEvent;
  8 import java.awt.event.ActionListener;
  9 import java.util.Collections;
 10 import java.util.Comparator;
 11 
 12 import java.util.Iterator;
 13 import java.util.LinkedHashMap;
 14 import java.util.LinkedList;
 15 import java.util.List;
 16 import java.util.Map;
 17 import java.util.Set;
 18 import java.util.TreeMap;
 19 
 20 import javax.swing.BorderFactory;
 21 import javax.swing.JButton;
 22 import javax.swing.JFrame;
 23 import javax.swing.JPanel;
 24 
 25 import org.jfree.chart.ChartColor;
 26 import org.jfree.chart.ChartFactory;
 27 import org.jfree.chart.ChartPanel;
 28 import org.jfree.chart.JFreeChart;
 29 import org.jfree.chart.axis.CategoryAxis;
 30 import org.jfree.chart.axis.ValueAxis;
 31 import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
 32 import org.jfree.chart.plot.CategoryPlot;
 33 import org.jfree.chart.plot.PlotOrientation;
 34 
 35 import org.jfree.chart.renderer.category.StackedBarRenderer3D;
 36 
 37 import org.jfree.data.category.CategoryDataset;
 38 import org.jfree.data.category.DefaultCategoryDataset;
 39 
 40 public class DisplayFace extends JFrame{
 41     private static final long serialVersionUID = 1L;
 42     public static TreeMap<String,Integer> map = WordFrequency.map;
 43     public static Set<String> key = map.keySet();
 44   
 45     public static int count1 = 0;
 46     public static int count2 = 0;
 47      public DisplayFace(){
 48       setTitle("词频统计程序");
 49       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 50       PanMain panMain = new PanMain(createDataSet());
 51       add(panMain);
 52      }
 53      
 54      @SuppressWarnings({ "unchecked", "static-access" })
 55     public static CategoryDataset createDataSet(){
 56          DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
 57          if(count1%2==0&&count2==0){
 58             WordFrequency wf = new WordFrequency();
 59             map = wf.map;
 60             
 61             for (Iterator<String> it = key.iterator(); it.hasNext();){
 62                 String s = it.next();
 63                 dataset.addValue((Integer)map.get(s),"",s);
 64             }
 65          }
 66          if(count1%2==1&&count2==0){
 67              WordFrequency wf = new WordFrequency();
 68                 map = wf.map;
 69                 TreeMap<String, Integer> map1 = new TreeMap<String, Integer>(new Comparator<String>(){  
 70                     public int compare(String o1, String o2) {  
 71                         return o2.compareTo(o1);  
 72                     }     
 73                 });  
 74                 for (Iterator<String> it = key.iterator(); it.hasNext();){
 75                     String s = it.next();
 76                     map1.put(s, map.get(s));    
 77                 }
 78                 Set<String> key1 = map1.keySet();
 79                 for (Iterator<String> it = key1.iterator(); it.hasNext();){
 80                     String s = it.next();
 81                     dataset.addValue((Integer)map1.get(s),"",s);
 82                 }
 83            }
 84             if(count1==0&&count2%2==0){
 85                 WordFrequency wf = new WordFrequency();
 86                 map = wf.map;
 87                 Map<String,Integer> map2 = new LinkedHashMap<String,Integer>();
 88                 map2 = sortByValue1(map);
 89                 Set<String> key2 = map2.keySet();
 90                 for (Iterator<String> it = key2.iterator(); it.hasNext();){
 91                     String s = it.next();
 92                     dataset.addValue((Integer)map2.get(s),"",s);
 93                     System.out.println(s+" : "+map2.get(s));        
 94                 }
 95                 
 96             }
 97             if(count1==0&&count2%2==1){
 98                 WordFrequency wf = new WordFrequency();
 99                 map = wf.map;
100                 Map<String,Integer> map3 = new LinkedHashMap<String,Integer>();
101                 map3 = sortByValue2(map);
102                 Set<String> key3 = map3.keySet();
103                 for (Iterator<String> it = key3.iterator(); it.hasNext();){
104                     String s = it.next();
105                     dataset.addValue((Integer)map3.get(s),"",s);
106                     System.out.println(s+" : "+map3.get(s));        
107                 }    
108             }
109          
110       return dataset;
111      }
112      @SuppressWarnings("unchecked")
113     public static Map sortByValue1(Map unsortMap) {
114             //value降序
115             List list = new LinkedList(unsortMap.entrySet());
116             Collections.sort(list, new Comparator(){
117                  public int compare(Object o1, Object o2){
118                      return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
119                  }
120              });
121              Map<String,Integer> sortedMap = new LinkedHashMap<String,Integer>();
122              for(Iterator it = list.iterator(); it.hasNext();){
123                  Map.Entry entry = (Map.Entry)it.next();
124                  sortedMap.put((String)entry.getKey(), (Integer)entry.getValue());
125              }
126           return sortedMap;
127      }
128      @SuppressWarnings("unchecked")
129     public static Map sortByValue2(Map unsortMap) {
130             //value升序
131             List list = new LinkedList(unsortMap.entrySet());
132             Collections.sort(list, new Comparator(){
133                  public int compare(Object o1, Object o2){
134                      return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
135                  }
136              });
137              Map<String,Integer> sortedMap = new LinkedHashMap<String,Integer>();
138              for(Iterator it = list.iterator(); it.hasNext();){
139                  Map.Entry entry = (Map.Entry)it.next();
140                  sortedMap.put((String)entry.getKey(), (Integer)entry.getValue());    
141              }
142           return sortedMap;
143      } 
144 
145      class PanMain extends JPanel{
146          private static final long serialVersionUID = 1L;
147          public PanMain(CategoryDataset dataSet){
148              this.setLayout(new BorderLayout());// 边框布局,使生成的柱形图随面板大小变化
149              setBorder(BorderFactory.createTitledBorder("词频统计"));
150   
151              JButton button1 = new JButton("单词");
152              JButton button2 = new JButton("词频");
153              button1.setPreferredSize(new Dimension(120,20));
154              button2.setPreferredSize(new Dimension(120,20));
155   
156              ChartPanel p = new ChartPanel(createdBarChart(dataSet));
157              p.add(button1);
158              p.add(button2);
159              add(p, BorderLayout.CENTER);
160   
161              button1.addActionListener(new ActionListener(){
162                  public void actionPerformed(ActionEvent e){
163                      count1++;
164                      count2=0;
165                      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
166                      DisplayFace frame = new DisplayFace();
167                      frame.setSize(600, 600);
168                      frame.setVisible(true);
169                      dispose();
170                  }
171             });
172   
173              
174            button2.addActionListener(new ActionListener(){
175                public void actionPerformed(ActionEvent e){
176                    count2++;
177                    count1=0;
178                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
179                    DisplayFace frame = new DisplayFace();
180                    frame.setSize(600, 600);
181                    frame.setVisible(true);
182                    dispose();
183               }
184           });
185        }
186  
187  
188        @SuppressWarnings("deprecation")
189     private JFreeChart createdBarChart(CategoryDataset dataSet){
190            JFreeChart jfreeChart = ChartFactory.createBarChart("词频统计",// 图表标题
191                    "单词",// 目录轴(一般为横轴)标题
192                    "单词数量",// 数据轴(一般为纵轴)标题
193                    dataSet, // 数据集
194                    PlotOrientation.HORIZONTAL, // 图表方向
195                    false,// 是否显示图例(对于简单的柱状图必须是false)
196                    true,// 是否生成工具
197                    false// 是否生成URL链接
198            );
199            CategoryPlot plot = (CategoryPlot) jfreeChart.getPlot();
200            // 获得目录轴 
201            plot.setBackgroundPaint(ChartColor.getHSBColor(20, 50, 30));
202            plot.setForegroundAlpha(1.0f); 
203   
204            CategoryAxis cAxis = plot.getDomainAxis();
205            // 设置目录轴坐标上文字的字体
206            cAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));
207            // 设置目录轴轴的标题文字的字体
208            cAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
209   
210            cAxis.setVisible(true);
211            cAxis.setAxisLineVisible(false);
212            cAxis.setTickMarksVisible(false);
213   
214            // 获得数据轴
215            ValueAxis vAxis = plot.getRangeAxis();
216            // 设置数据轴坐标上的文字的字体
217            vAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));
218            // 设置数据轴的标题文字的字体
219            vAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
220            vAxis.setVisible(false);
221   
222            StackedBarRenderer3D render=new StackedBarRenderer3D();
223            render.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
224            render.setItemLabelFont(new Font("黑体",Font.PLAIN,9));
225            render.setItemLabelsVisible(true);
226            render.setItemMargin(0.1);
227            //render.setSeriesItemLabelsVisible(1, false);
228            plot.setRenderer(render);
229            
230            return jfreeChart;    
231            }
232        }
233 }
234     

程序截图:

原文地址:https://www.cnblogs.com/ldk999/p/2979950.html