zoukankan      html  css  js  c++  java
  • 输出《Harry Potter and the Sorcerer's Stone》文本中的前N个最长用的英文单词及其数量

    输出《Harry Potter and the Sorcerer's Stone》文本中的前N个最长用的英文单词及其数量

    实验思路:

    1. 利用输入流将文件当中内容读入。

    2. 将文件内容存入StringBuffer中;

    3. 利用String的split()方法将字符串分隔,并将其存入数组中;

    4. 遍历数组将其存入Map<String, Integer>中

    5. 利用Collections的sort()方法进行排序。

    6.输出打印。

    import java.io.*;
    import java.util.*;
    import java.util.Map.Entry;
    public class two 
    {
    	 public static int n=0;
         public static void main(String[] args) {
         Scanner input=new Scanner(System.in);
        
         int count=0;
         int num=1;
         String file1="Harry Potter and the Sorcerer's Stone.txt";
         try
         {
           BufferedReader a=new BufferedReader(new FileReader(file1));
           StringBuffer c=new StringBuffer();
           String s;
           while((s = a.readLine()) != null) 
           {
                 c.append(s);
           }
           String m=c.toString().toLowerCase();
           String [] d=m.split("[^a-zA-Z0-9]+");
           Map<String , Integer> myTreeMap=new  TreeMap<String, Integer>();
           for(int i = 0; i < d.length; i++) {
               
                 if(myTreeMap.containsKey(d[i])) {
                     count = myTreeMap.get(d[i]);
                     myTreeMap.put(d[i], count + 1);
                 }
                 else {
                     myTreeMap.put(d[i], 1);
                 }
             } 
           List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(myTreeMap.entrySet());
         //按降序排序
           Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
               
                 public int compare(Entry<String, Integer> k1, Entry<String, Integer> k2) {
                     return k2.getValue().compareTo(k1.getValue());
                 }
                 
             });
            System.out.println("请输入N的值:");
             n=input.nextInt();
           for(Map.Entry<String, Integer> map : list) {
                 if(num <= n) {
            
                     System.out.println(map.getKey() + ":" + map.getValue());
                     num++;
                 }
                 else break;
             }
             a.close();
         }
         catch(FileNotFoundException e)
         {
            
         }
         catch(IOException e)
         {
            
         }
     }
     }
    

      

  • 相关阅读:
    Jzoj4822 完美标号
    Jzoj4822 完美标号
    Jzoj4792 整除
    Jzoj4792 整除
    Educational Codeforces Round 79 A. New Year Garland
    Good Bye 2019 C. Make Good
    ?Good Bye 2019 B. Interesting Subarray
    Good Bye 2019 A. Card Game
    力扣算法题—088扰乱字符串【二叉树】
    力扣算法题—086分隔链表
  • 原文地址:https://www.cnblogs.com/zwx655/p/11806321.html
Copyright © 2011-2022 走看看