zoukankan      html  css  js  c++  java
  • java统计文本中单词出现的个数

    package com.java_Test;
    
    import java.io.File;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
    
    public class test {
        public static void main(String[] args) throws Exception {
            new test().wordCount();
        }//统计文本中单词出现的个数
        public void wordCount() throws Exception{
            File file=new File("text3.txt");
            Scanner sc=new Scanner(file);
            HashMap<String,Integer> hashMap=new HashMap<>();
            System.out.println("文章----------------------");
            while(sc.hasNextLine()){
                String line=sc.nextLine();
                System.out.print(line+" ");
                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);
                    }
                }
            }
            System.out.println("统计单词------------------");
            Iterator<String> iterator=hashMap.keySet().iterator();
            while(iterator.hasNext()){
                String word=iterator.next();
                System.out.printf("单词:%-12s   出现次数:%d
    ",word,hashMap.get(word));
            }
        }
    }
  • 相关阅读:
    URAL 1948 H
    int、long、long long取值范围
    Bonetrousle HackerRank 数学 + 思维题
    湖南省第十二届大学生计算机程序设计竞赛 problem A 2016
    Abbreviation ---- hackerrank
    POJ 3321 Apple Tree DFS序 + 树状数组
    HDU
    PICO CTF 2013 PHP 2: 85
    XSS进阶三
    XSS进阶二
  • 原文地址:https://www.cnblogs.com/zk-blog/p/10003158.html
Copyright © 2011-2022 走看看