编程:统计一段文本中每个单词出现的次数,使用一个HashMap来实现。
时间: 2024-02-27 19:57:55 浏览: 87
好的,以下是Java代码示例:
```java
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String text = "This is a sample text with repeated words. Sample text is used to demonstrate the word count program. The program counts the number of times each word appears in the text.";
// 将所有单词转换为小写,以便统计时不区分大小写
text = text.toLowerCase();
// 将标点符号替换为空格,以便单词能够正确分割
text = text.replaceAll("[^a-zA-Z0-9 ]", " ");
// 将文本分割为单词数组
String[] words = text.split("\\s+");
// 使用HashMap统计每个单词出现的次数
HashMap<String, Integer> wordCounts = new HashMap<>();
for (String word : words) {
if (wordCounts.containsKey(word)) {
wordCounts.put(word, wordCounts.get(word) + 1);
} else {
wordCounts.put(word, 1);
}
}
// 输出结果
for (String word : wordCounts.keySet()) {
System.out.println(word + " : " + wordCounts.get(word));
}
}
}
```
代码中,我们首先将文本中的所有单词转换为小写,然后使用正则表达式将标点符号替换为空格,以便单词能够正确分割。然后,我们使用HashMap统计每个单词出现的次数,最后输出结果。
阅读全文