• 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));
            }
        }
    }
  • 相关阅读:
    区块链入门
    上海美食餐厅
    《OD学hadoop》20160910某旅游网项目实战
    《OD学hadoop》20160904某旅游网项目实战
    《OD学hadoop》20160903某旅游网项目实战
    qt5-自定义类
    qt5-Qt Creator使用
    qt5-QPushButton按钮
    qt5-工程文件的介绍--快捷键
    电路分析-电阻
  • 原文地址:https://www.cnblogs.com/zk-blog/p/10003158.html
Copyright © 2020-2023  润新知