一、 實驗要求:java
實驗報告中要求包括程序設計思想、程序流程圖、源代碼、運行結果截圖、編譯錯誤分析等內容。spa
2、實驗內容:設計
(1) 用戶需求:英語的26 個字母的頻率在一本小說中是如何分佈的?某類型文章中常出現的單詞是什麼?某做家最經常使用的詞彙是什麼?《哈利波特》 中最經常使用的短語是什麼,等等。code
要求:輸出單個文件中的前 N 個最常出現的英語單詞,並將結果輸入到文本文件中。blog
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 }
運行截圖:get