欢迎访问宙启技术站
智能推送

编写Java函数来统计文本中单词出现的次数

发布时间:2023-06-13 12:21:11

在Java中,我们可以使用HashMap来实现统计单词出现的次数。具体实现如下:

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

public class WordCount {

    public static Map<String, Integer> countWords(String text) {
        // 创建一个HashMap用于存储单词和出现次数
        Map<String, Integer> wordCount = new HashMap<>();

        // 将文本中的单词按照空格分割成字符串数组
        String[] words = text.split("\\s+");

        // 遍历字符串数组,统计每个单词出现的次数
        for (String word : words) {
            // 将单词全部转换为小写,忽略大小写
            String cleanWord = word.toLowerCase();
            if (wordCount.containsKey(cleanWord)) {
                // 如果单词已经出现过,则将其出现次数加一
                wordCount.put(cleanWord, wordCount.get(cleanWord) + 1);
            } else {
                // 如果单词      次出现,则将其出现次数设为1
                wordCount.put(cleanWord, 1);
            }
        }

        // 返回统计结果
        return wordCount;
    }

    public static void main(String[] args) {
        String text = "Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications.";

        Map<String, Integer> wordCount = countWords(text);

        // 输出统计结果
        for (String word : wordCount.keySet()) {
            System.out.println(word + ": " + wordCount.get(word));
        }
    }
}

在上述代码中,我们定义了一个名称为countWords的静态方法,它接收一个字符串参数text表示要统计单词的文本,返回一个Map<String, Integer>类型的结果,表示单词和出现次数的键值对。

首先,在方法内部创建一个HashMap用于存储单词和出现次数。然后,将文本中的单词按照空格分割成字符串数组。接下来,遍历字符串数组,统计每个单词出现的次数。

在计算每个单词的出现次数时,我们将单词全部转换为小写,忽略大小写。如果单词已经出现过,则将其出现次数加一;如果单词 次出现,则将其出现次数设为1。

最后,返回统计结果。

main方法中,我们定义了一个文本变量,将其传递给countWords方法进行统计。然后,遍历统计结果并输出每个单词的出现次数。输出结果如下所示:

business: 1
programming: 1
sun: 1
platform: 1
is: 2
and: 2
state-of-the-art: 1
java: 1
including: 1
microsystems: 1
computing: 1
released: 1
it: 2
applications.: 1
language: 1
utilities,: 1
first: 1
games,: 1
powers: 1
by: 1
1995.: 1
a: 2

通过上述代码可以看出,我们可以使用HashMap来在Java中统计文本中单词出现的次数。