本文介绍了如何计算每个单词的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一篇英文文章或一本英文小说,我想计算每个单词出现的次数,用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
更多推荐
如何计算每个单词的出现次数?
发布评论