Awang2623

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

统计文章中各个英语单词出现的次数:

import java.io.*;
import java.util.*;
 public class Tongji {
     public static <type> void main (String[] args) throws FileNotFoundException {
         File file=new File("D:\\english.txt");                  //读取文件
         Scanner input=new Scanner(file);
         HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
         while(input.hasNextLine()) {
             String line=input.nextLine();
             String[] lineWords=line.split("\\W+");          
             Set<String> wordSet=hashMap.keySet();
             for(int i=0;i<lineWords.length;i++) {
                 if(wordSet.contains(lineWords[i])) {
                     Integer number=hashMap.get(lineWords[i]);
                     number++;
                     hashMap.put(lineWords[i], number);  
                     }
                 else {
                     hashMap.put(lineWords[i], 1);
                 }
             }
         }
         for (String key : hashMap.keySet()) {
             System.out.println(key+"出现:"+hashMap.get(key)+"次");
         }
       
     }
 }

结果:

 

posted on 2019-05-05 19:27  Awang2623  阅读(380)  评论(0)    收藏  举报