代码改变世界

统计分析

2018-10-14 22:20  一念永恒s  阅读(279)  评论(0编辑  收藏  举报

1. 设计思路:利用文件的输入和输出对文章进行操作,通过数组将字符串进行分配,然后对字符串进行比较,最后判断出来文章中出现的最多的单词是哪个

2.源代码

 

 1 package 字母频率统计;
 2   import java.io.*;
 3   import java.util.*;
 4   public class Ciyu {
 5   public static <type> void main (String[] args) throws FileNotFoundException {
 6   File file=new File("D://a.txt");                  //读取文件
 7           if(!file.exists()){//如果文件打不开或不存在则提示错误
 8              System.out.println("文件不存在");
 9               return;
10          }   
11          Scanner x=new Scanner(file);
12          HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
13       while(x.hasNextLine()) {
14       String line=x.nextLine();
15       String[] lineWords=line.split("\\W+");          
16       Set<String> wordSet=hashMap.keySet();
17             for(int i=0;i<lineWords.length;i++) {
18                 if(wordSet.contains(lineWords[i])) {
19                     Integer number=hashMap.get(lineWords[i]);
20                     number++;
21                      hashMap.put(lineWords[i], number);  
22                     }
23                  else {
24                     hashMap.put(lineWords[i], 1);
25                  }
26            }
27        }
28         Iterator<String> iterator=hashMap.keySet().iterator();
29          int max=0;
30          String maxword=null;
31          while(iterator.hasNext()){
32             String word=iterator.next();
33              if(hashMap.get(word)>max) {//比较出现次数最多的单词
34                  max=hashMap.get(word);
35                  maxword=word; 
36            }
37          }           System.out.println("本篇文章中出现次数最多的单词是"+maxword);
38         System.out.println("共出现了"+max+"次");
39     }
40  }