如何计算每个单词的出现次数? [英] How to count the number of occurrences of each word?

查看:149
本文介绍了如何计算每个单词的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一篇英文文章或一本英文小说,我想计算每个单词出现的次数,用Java编写的最快的算法是什么?

If I have an article in English, or a novel in English, and I want to count how many times each words appears, what is the fastest algorithm written in Java?

有人说你可以使用地图< String,Integer>()来完成这个,但我想知道我怎么知道是什么关键词?

Some people said you can use Map < String, Integer>() to complete this, but I was wondering how do I know what is the key words? Every article has different words and how do you know the "key" words then add one on its count?

推荐答案

    Map<String, Integer> countByWords = new HashMap<String, Integer>();
    Scanner s = new Scanner(new File("your_file_path"));
    while (s.hasNext()) {
        String next = s.next();
        Integer count = countByWords.get(next);
        if (count != null) {
            countByWords.put(next, count + 1);
        } else {
            countByWords.put(next, 1);
        }
    }
    s.close();

这个计数I'm只有一个字

this count "I'm" as only one word

这篇关于如何计算每个单词的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆