java-统计一段句子中各单词出现的次数

问题:统计一段句子中各单词出现的次数。

思路:
1、使用split方法将文章进行分割,我们这里以空格、逗号和句点为分隔符,然后存到一个字符串数组中。

2、创建一个hashMap集合,key是字符串类型,保存单词;value是数字类型,保存该单词出现的次数。

3、遍历思路1中的字符串数组,如果key(单词)没有出现过,map中增加一个元素,key为该单词,定义value为1;如果key(单词)出现过,那么value的值加1。

4.遍历输入key及其对应的value值。
具体代码如下:
StrList类,实现统计单词出现次数的方法。

package wordCounts;

import java.util.HashMap;
import java.util.Map.Entry;

public class StrList {
    public  String StatList(String s) {
        StringBuffer sb = new StringBuffer();
        HashMap<String, Integer> has = new HashMap<String,Integer>();//打开哈希表,字符类型储存key(单词),整型储存value(单词出现的次数)
        String[] sList = s.split(" |,|\\.");//使用split方法将字符串s按空格、逗号和句点分割开,并存在字符数组sList中
        for(int i=0; i<sList.length; i++){//遍历sList数组
            if(!has.containsKey(sList[i])){//如果没有这个单词,就将单词存入key里,value值为1;containsKey方法 判断集合中是否包含指定的key
                has.put(sList[i], 1);
            }else{//如果已经存在,就将value值加1;用get方法获取key对应的value值
                has.put(sList[i], has.get(sList[i])+1);
            }
        }
        //使用增强for循环遍历,通过Entry集合访问,可以访问key及其对应的Value值
        for(Entry<String, Integer> entry:has.entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        return sb.toString();
    }
}

main方法(创建另一个类):
方式一:已经指定好了句子

package wordCounts;
import java.util.Scanner;

public class WordCounts{
    public static void main(String[] args) {
        String sentence = "The most distant way in the world,"
                + "is not the way from birth to the end. "
                + "It is when I stand in front of you,"
                + "but you don't understand I love you.";

        System.out.println(StatList(sentence));
    }

}

方式二:从键盘输入

package wordCounts;
import java.util.Scanner;
public class WordCounts{
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        String ab = scanner.nextLine();

        StrList sl = new StrList();
        System.out.println(sl.StatList(ab));
    }

}

猜你喜欢

转载自blog.csdn.net/soda_lw/article/details/77964272