zoukankan      html  css  js  c++  java
  • 用java 集合和映射实现文章的单词数目统计

    package 一_统计字母出现;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
     
    public class worldcont
    {
        public static void main(String[] args) throws FileNotFoundException//表示这个方法有可能会发生找不到文件这个错误。
        {
            File file=new File("F:/eclipse/工程项目作业/english_essay.txt");
            if(!file.exists())
            {
                System.out.println("文件不存在");
                return;
            }
            Scanner scanner=new Scanner(file);
            //单词和数量映射表
            HashMap<String, Integer > hashMap=new HashMap<String,Integer>();
            System.out.println("文章-----------------------------------");
            while(scanner.hasNextLine())
            {
                String line=scanner.nextLine();
                System.out.println(line);
                //W+ : 匹配所有非单词
                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);
                    }
                }
                
            }
          
            Iterator<String> iterator=hashMap.keySet().iterator();
            while(iterator.hasNext())
            {
                String word=iterator.next();
                
    //            System.out.printf("单词: "+word+"出现次数:"+hashMap.get(word));
                System.out.printf("单词:%-12s 出现次数:%d
    ",word,hashMap.get(word));
            }
            
            
           
        }
    }
  • 相关阅读:
    select()函数用法二
    fcntl函数的用法总结
    O_NONBLOCK与O_NDELAY有何不同?
    struct termios结构体详解
    select()函数用法一
    linux下的struct sigaction
    sigaction 用法实例
    nand flash 的oob 及坏块管理
    wifi两种工作模式
    UBIFS文件系统简介 与 利用mkfs.ubifs和ubinize两个工具制作UBI镜像 (完整理解版本)
  • 原文地址:https://www.cnblogs.com/zhang188660586/p/9775272.html
Copyright © 2011-2022 走看看