统计分析

1、     实验要求:

实验报告中要求包括程序设计思想、程序流程图、源代码、运行结果截图、编译错误分析等内容。

2、实验内容:

(1)  用户需求:英语的26 个字母的频率在一本小说中是如何分布的?某类型文章中常出现的单词是什么?某作家最常用的词汇是什么?《哈利波特》 中最常用的短语是什么,等等。

要求:输出单个文件中的前 N 个最常出现的英语单词,并将结果输入到文本文件中。

 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         }   
38         System.out.println("本篇文章中出现次数最多的单词是"+maxword);
39         System.out.println("共出现了"+max+"次");
40     }
41 }

运行截图:

原文地址:https://www.cnblogs.com/mawangwang/p/9787208.html