java实现单词计数(附完整源码)
时间: 2023-11-09 14:07:43 浏览: 40
下面是Java实现单词计数的示例代码:
```java
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static Map<String, Integer> countWords(String text) {
Map<String, Integer> wordCount = new HashMap<>();
String[] words = text.split("\\s+");
for (String word : words) {
word = word.toLowerCase().replaceAll("[^a-z0-9]", "");
if (!word.isEmpty()) {
int count = wordCount.getOrDefault(word, 0);
wordCount.put(word, count + 1);
}
}
return wordCount;
}
public static void main(String[] args) {
String text = "Hello world, this is a sample text. "
+ "It contains words, punctuation marks, and numbers like 1234.";
Map<String, Integer> wordCount = countWords(text);
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
上述代码使用了HashMap来存储单词及其出现次数。首先将文本按空格分割成单词,然后对于每个单词,将其转换为小写并去除非字母数字字符,最后将其加入到HashMap中。如果HashMap中已有该单词,则将其出现次数加1。最终返回单词计数结果。